我认为数组是不可复制的
我的印象是数组是不可复制(或可分配)的。
int x[5] = {1,2,3,4,5};
int y[5] = {6,7,8,9,0};
x = y; // Fails to compile
但是,当我将数组放入类中时,复制构造函数和赋值运算符会起作用(我会说如预期的那样,但它不是我所预期的)。
#include <iostream>
struct X
{
virtual ~X(){} // Just in case it was something to do with POD
// make sure its not a POD
int x[5];
};
int main()
{
X a;
a.x[0] = 0;
a.x[1] = 1;
a.x[2] = 2;
a.x[3] = 3;
a.x[4] = 4;
// Make a copy of a and test it
X b(a);
std::cout << a.x[0] << " : " << b.x[0] << "\n";
b.x[0] = 10;
b.x[1] = 11;
b.x[2] = 12;
b.x[3] = 13;
b.x[4] = 14;
// Now that we have modified 'b' make sure it is unique.
std::cout << a.x[0] << " : " << b.x[0] << "\n";
// Use assignment and see if it worked.
b = a;
std::cout << a.x[0] << " : " << b.x[0] << "\n";
}
编译并运行
> g++ t.cpp
> ./a.out
0 : 0
0 : 10
0 : 0
这里发生了什么?
I was under the impression that array were non copyable (or assignable).
int x[5] = {1,2,3,4,5};
int y[5] = {6,7,8,9,0};
x = y; // Fails to compile
But when I put an array inside a class the copy constructor and assignment operator work (I would say as expected but its not what I expected).
#include <iostream>
struct X
{
virtual ~X(){} // Just in case it was something to do with POD
// make sure its not a POD
int x[5];
};
int main()
{
X a;
a.x[0] = 0;
a.x[1] = 1;
a.x[2] = 2;
a.x[3] = 3;
a.x[4] = 4;
// Make a copy of a and test it
X b(a);
std::cout << a.x[0] << " : " << b.x[0] << "\n";
b.x[0] = 10;
b.x[1] = 11;
b.x[2] = 12;
b.x[3] = 13;
b.x[4] = 14;
// Now that we have modified 'b' make sure it is unique.
std::cout << a.x[0] << " : " << b.x[0] << "\n";
// Use assignment and see if it worked.
b = a;
std::cout << a.x[0] << " : " << b.x[0] << "\n";
}
Compile and Run
> g++ t.cpp
> ./a.out
0 : 0
0 : 10
0 : 0
What is going on here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
默认的复制构造函数和赋值运算符对每个成员单独使用复制构造和赋值。当存在数组时,会对数组的每个元素使用复制构造或赋值(这是非常明确定义的)。
这是第 12.8 节 (
[class.copy]
) 中的规则:和
C::C(const C&)
与C::C(C&)
等之间的签名选择规则还包括引用数组元素类型的语言。The defaulted copy constructor and assignment operator use copy construction and assignment individually on each member. When there's an array, copy construction or assignment is used on each element of the array (which is quite well-defined).
Here's the rule, from section 12.8 (
[class.copy]
):and
The rule for signature selection between
C::C(const C&)
vsC::C(C&)
et al also includes language referring to the array element type.数组既不可复制也不可赋值。然而,具有数组成员的结构已经生成了复制构造和复制赋值。这是一个特殊的规则:即它们本身不需要可复制或可分配。
Arrays are neither copyable nor assignable. However, structure with array members have generated copy construction and copy assignment. This is a special rule: i.e. they don't need to be copyable or assignable themselves.