c++c++11compiler-optimizationmove-semantics

If Move semantics(Move constructor and Move assignment operator) are not defined does compiler optimize by default?


While defining class if we forget to write Move constructor and Move assignment operator does compiler is smart enough to optimize and add automatically.


Solution

  • Maybe, maybe not. It's not a question of whether the compiler is smart enough, but what other special member functions you have remembered, or forgotten, to define. The exact conditions when a move constructor will be implicitly defined by the compiler are listed under §12.8/9 [class.copy]

    If the definition of a class X does not explicitly declare a move constructor, one will be implicitly declared as defaulted if and only if
    X does not have a user-declared copy constructor,
    X does not have a user-declared copy assignment operator,
    X does not have a user-declared move assignment operator, and
    X does not have a user-declared destructor.

    Similarly, the conditions for implicit generation of a move assignment operator are listed under §12.8/20

    If the definition of a class X does not explicitly declare a move assignment operator, one will be implicitly declared as defaulted if and only if
    X does not have a user-declared copy constructor,
    X does not have a user-declared move constructor,
    X does not have a user-declared copy assignment operator, and
    X does not have a user-declared destructor.