Search code examples
c++language-lawyer

copy and assignment operator with constant size arrays


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


Solution

  • The 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;
    ...