Why doesn’t the compiler auto-generate a move constructor?
The compiler does generate a move constructor if you don’t do so – after a fashion. However, the compiler cannot second-guess your motives so it doesn’t know what the pointer in your class does. In particular, it doesn’t know that the pointer confers ownership of memory and needs to be nulled out.
Is the implementation of the move constructor correct?
The move constructor is correct1 but the rest of the class isn’t, you are violating the rule of three: your class needs an appropriate copy constructor and copy assignment operator.
Is there a better way to implement the move constructor?
A better way to write the move constructor looks as follows:
MyClass(MyClass&& rcOther) : mpiSize(std::move(rcOther.mpiSize)) , miSize2(std::move(rcOther.miSize2)) { rcOther.mpiSize = 0; }
Two comments:
- Why did you not directly copy the members, instead dereferencing
rcOther.mpiSize? While this isn’t wrong, it also makes no sense and is misleading. - You do not need to zero out the integer, and since it’s unnecessary it shouldn’t be done: The only modification your move constructor should perform on the moved-from object is to relinquish ownership of its resources so that it can be destroyed without causing resources to be doubly deleted.
But an even better way is to rely on pre-existing facilities. In this case, you want to model memory ownership. A naked pointer does this poorly, you should use a std::unique_ptr instead. This way, you don’t need to implement either destructor nor move constructor since the the auto-generated methods do the right thing.
1 Caveat: See Seth’s answer for a better explanation that mentions std::move (which is a no-op in this particular case, however).