Suppose this class in C++
class Message {
char msg[64];
};
Why are operator=
and default copy already correct
Message & operator=(const Message &o) {
if (this != &o)
this->msg = o.msg;
}
return *this;
}
In assignment should be wrong?
Isn't it the default semantics to use assignment operator field per field to implement default assignment and copy construction
Suppose this class in C++
class Message {
char msg[64];
};
Why are operator=
and default copy already correct
Message & operator=(const Message &o) {
if (this != &o)
this->msg = o.msg;
}
return *this;
}
In assignment should be wrong?
Isn't it the default semantics to use assignment operator field per field to implement default assignment and copy construction
Share Improve this question edited Jan 17 at 17:18 Yann TM asked Jan 17 at 15:04 Yann TMYann TM 2,07515 silver badges23 bronze badges 11 | Show 6 more comments1 Answer
Reset to default 9The implicitly-defined copy assignment operator is not as simple as "apply assignment to each member". Arrays are specifically taken into account as a special case.
[class.copy.assign]/12 The implicitly-defined copy/move assignment operator for a non-union class
X
performs memberwise copy/move assignment of its subobjects... Each subobject is assigned in the manner appropriate to its type:
...
(12.2) if the subobject is an array, each element is assigned, in the manner appropriate to the element type;
...
o.mg
– Louis Go Commented Jan 17 at 15:07memcpy
. In any case, the member that's an array of objects that are not trivially copyable works just as well. – Igor Tandetnik Commented Jan 17 at 15:25