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?
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.