c++c++11language-lawyertrivially-copyable

Do all special member functions need to be trivial for a class to be trivially copyable?


The cppreference page for the named requirement of being TriviallyCopyable, in the subsection for classes, lists the following requirement:

Trivially copyable class

A trivially copyable class is a class that

  • has at least one eligible copy constructor, move constructor, copy assignment operator, or move assignment operator,
  • each eligible copy constructor is trivial
  • each eligible move constructor is trivial
  • each eligible copy assignment operator is trivial
  • each eligible move assignment operator is trivial, and
  • has a non-deleted trivial destructor.

so, if there's a trivial copy ctor but a non-trivial, say, move assignment operator - isn't the class trivially copyable? My intuition says that if you can construct an object of the same type by (trivially) memcpying the existing object (or assigning-by-memcpy to a constructed object) - that's trivial copyability.


Solution

  • so, if there's a trivial copy ctor but a non-trivial, say, move assignment operator - isn't the class trivially copyable?

    No, not if the copy constructor and move assignment operator are eligible, according to the C++23 standard:

    11.2. Properties of classes [class.prop]

    1. A trivially copyable class is a class:

      1.1. — that has at least one eligible copy constructor, move constructor, copy assignment operator, or move assignment operator ([special], [class.copy.ctor], [class.copy.assign]),

      1.2. — where each eligible copy constructor, move constructor, copy assignment operator, and move assignment operator is trivial, and

      1.3. — that has a trivial, non-deleted destructor ([class.dtor]).

    2. A trivial class is a class that is trivially copyable and has one or more eligible default constructors ([class.default.ctor]), all of which are trivial.

      [Note 1 : In particular, a trivially copyable or trivial class does not have virtual functions or virtual base classes. — end note]

    11.4.4. Special member functions

    1. An eligible special member function is a special member function for which:

      6.1. the function is not deleted,

      6.2. the associated constraints, if any, are satisfied, and

      6.3. no special member function of the same kind is more constrained