Reputation: 866
C++ does not allow copying of C-style arrays using =
. But allows copying of structures using =
, as in this link -> Copying array in C v/s copying structure in C.It does not have any credible answers yet.
But consider following code
#include <iostream>
using namespace std;
struct user {
int a[4];
char c;
};
int main() {
user a{{1,2,3,4}, 'a'}, b{{4,5,6,7}, 'b'};
a = b; //should have given any error or warning but nothing
return 0;
}
Above code segment didn't gave any kind of errors and warnings, and just works fine. WHY? Consider explaining both questions(this one and the one linked above).
Upvotes: 5
Views: 835
Reputation: 117308
Your class user
gets an implicitly declared copy constructor and implicitly declared copy assignment operator.
The implicitly declared copy assignment operator copies the content from b
to a
.
Two passages from the standard that seems to apply:
if the member is an array, each element is direct-initialized with the corresponding subobject of x;
if the subobject is an array, each element is assigned, in the manner appropriate to the element type;
Upvotes: 9
Reputation: 172934
Yes, the code should work fine. arrays can't be assigned directly as a whole; but they can be assigned as data member by the implicity-defined copy assignment operator, for non-union class type it performs member-wise copy assignment of the non-static data member, including the array member and its elements.
Objects of array type cannot be modified as a whole: even though they are lvalues (e.g. an address of array can be taken), they cannot appear on the left hand side of an assignment operator:
int a[3] = {1, 2, 3}, b[3] = {4, 5, 6}; int (*p)[3] = &a; // okay: address of a can be taken a = b; // error: a is an array struct { int c[3]; } s1, s2 = {3, 4, 5}; s1 = s2; // okay: implicity-defined copy assignment operator // can assign data members of array type
Upvotes: 5