Search code examples
c++c++11copymovemove-constructor

Is it safe to rely on an implicitly declared move constructor?


This is where I got most of this information: http://en.cppreference.com/w/cpp/language/move_constructor

Apparently these are the conditions for the implicitly generated move constructor to work:

  • 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
  • the implicitly-declared move constructor is not defined as deleted
  • if a user declared move constructor is present, it is still possible to still force the generation of the implicitly declared move constructor with the keyword default

My questions are:

  1. Is it safe to rely on implicit automatic move constructor?
  2. How do I check if it really worked instead of default copy constructor?
  3. Finally, and most importantly, is it a good idea and why? Or is it always better to define my own?

I am more inclined to follow the rule of three and manually create a destructor, a copy and move constructor, and a copy and move assignment operator, but I'm just curious about this implicit one.


Solution

  • Here are the answers to your questions:

    1. What do you mean with "safe"? When the rules apply, i.e., the subobjects are movable and you didn't do anything to stomp on the generation of the move constructor, it will be created and used when present. Note, however, that it is easy to have a non-movable subobject which will somewhat invisibly inhibit the creation of a move constructor.
    2. To see if your class got a move constructor, just temporarily add an empty base logging when the copy and the move constructors are used and force the object to be moved/copied: it will log the correspondingly used constructor.
    3. No code is generally better than any code.