我想知道这段代码是如何工作的:
struct my_array
{
int r[1000];
};
int main()
{
my_array foo, bar;
foo = bar;
}
因为 foo = bar
调用将为类调用构造函数提供的 operator=
,这将延迟将其应用于每个成员。但是数组没有 operator=
的实现,证据是,这段代码无法编译:
int main()
{
int a[1000], b[1000];
a = b;
}
那么我的第一个代码是如何编译的呢?
最佳答案
So how come my first code compiles?
语言规范规定它必须工作,并且编译器实现了该行为。
默认赋值语义在 § 12.8 [class.copy] 的第 28 条中指定。具体来说,对象的数据成员是一个一个赋值的。在数组的情况下,数组的元素被一一分配。
The implicitly-defined copy/move assignment operator for a non-union class X performs memberwise copy- /move assignment of its subobjects. ...
和
— if the subobject is an array, each element is assigned, in the manner appropriate to the element type;
(强调我的)
请注意,在您的特定示例中,第一个代码示例调用未定义的行为,因为 bar
的元素在您从此处读取它们时未初始化:
foo = bar; // UB: bar.r uninitialized
你可以通过适当的初始化 bar
来解决这个问题:
my_array foo;
my_array bar{};
关于c++ - 在数组上调用赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34491686/