Search code examples
c++c++11constructordefaultmove-semantics

Is a `=default` move constructor equivalent to a member-wise move constructor?


Is this

struct Example { 
    string a, b; 

    Example(Example&& mE) : a{move(mE.a)}, b{move(mE.b)} { }
    Example& operator=(Example&& mE) { a = move(mE.a); b = move(mE.b); return *this; } 
}

equivalent to this

struct Example { 
    string a, b;

    Example(Example&& mE)            = default;
    Example& operator=(Example&& mE) = default;
}

?


Solution

  • Yes both are the same.

    But

    struct Example { 
        string a, b; 
    
        Example(Example&& mE)            = default;
        Example& operator=(Example&& mE) = default;
    }
    

    This version will permits you to skip the body definition.

    However, you have to follow some rules when you declare explicitly-defaulted-functions :

    8.4.2 Explicitly-defaulted functions [dcl.fct.def.default]

    A function definition of the form:

      attribute-specifier-seqopt decl-specifier-seqopt declarator virt-specifier-seqopt = default ;
    

    is called an explicitly-defaulted definition. A function that is explicitly defaulted shall

    • be a special member function,

    • have the same declared function type (except for possibly differing ref-qualifiers and except that in the case of a copy constructor or copy assignment operator, the parameter type may be “reference to non-const T”, where T is the name of the member function’s class) as if it had been implicitly declared,

    • not have default arguments.