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).
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:
class.copy.ctor
if the member is an array, each element is direct-initialized with the corresponding subobject of x;
class.copy.assign
if the subobject is an array, each element is assigned, in the manner appropriate to the element type;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With