10

Do compilers (let us use g++ as the specific example) provide a default move constructor and default move assignment operator when we write a class?

Compilers provide a default:

  • Constructor (no arguments) unless another constructor with arguments is declared.
  • Destructor (which presumably does nothing? - actually not quite, this question has an answer here, it calls the base class destructor)
  • Copy Constructor unless we write our own
  • Copy Assignment Operator unless we write our own

Will a compiler provide a default move constructor or move assignment operator.

FreelanceConsultant
  • 13,167
  • 27
  • 115
  • 225

1 Answers1

6

According to cppreference:

Implicitly-declared move constructor

If no user-defined move constructors are provided for a class type (struct, class, or union), and all of the following is true:

  • there are no user-declared copy constructors
  • there are no user-declared copy assignment operators
  • there are no user-declared move assignment operators
  • there are no user-declared destructors (until C++14) the implicitly-declared move constructor is not defined as deleted due to conditions detailed in the next section

then the compiler will declare a move constructor as a non-explicit inline public member of its class with the signature T::T(T&&).

A class can have multiple move constructors, e.g. both T::T(const T&&) and T::T(T&&). If some user-defined move constructors are present, the user may still force the generation of the implicitly declared move constructor with the keyword default.

And according to cppreference:

Implicitly-declared move assignment operator

If no user-defined move assignment operators are provided for a class type (struct, class, or union), and all of the following is true:

  • there are no user-declared copy constructors
  • there are no user-declared move constructors
  • there are no user-declared copy assignment operators
  • there are no user-declared destructors (until C++14) the implicitly-declared move assignment operator would not be defined as deleted

then the compiler will declare a move assignment operator as an inline public member of its class with the signature T& T::operator=(T&&).

A class can have multiple move assignment operators, e.g. both T& T::operator=(const T&&) and T& T::operator=(T&&). If some user-defined move assignment operators are present, the user may still force the generation of the implicitly declared move assignment operator with the keyword default.

Because some assignment operator (move or copy) is always declared for any class, the base class assignment operator is always hidden. If a using-declaration is used to bring in the assignment operator from the base class, and its argument type could be the same as the argument type of the implicit assignment operator of the derived class, the using-declaration is also hidden by the implicit declaration.

FreelanceConsultant
  • 13,167
  • 27
  • 115
  • 225