Elliot Hatch Elliot Hatch - 1 year ago 77
C++ Question

Implementing Move Constructor by Calling Move Assignment Operator

The MSDN article, How to: Write a Move Constuctor, has the following recommendation.

If you provide both a move constructor and a move assignment operator for your class, you can eliminate redundant code by writing
the move constructor to call the move assignment operator. The
following example shows a revised version of the move constructor that
calls the move assignment operator:

// Move constructor.
MemoryBlock(MemoryBlock&& other)
: _data(NULL)
, _length(0)
*this = std::move(other);

Is this code inefficient by doubly initializing
's values, or will the compiler be able to optimize away the extra initializations? Should I always write my move constructors by calling the move assignment operator?

Answer Source

I wouldn't do it this way. The reason for the move members to exist in the first place is performance. Doing this for your move constructor is like shelling out megabucks for a super-car and then trying to save money by buying regular gas.

If you want to reduce the amount of code you write, just don't write the move members. Your class will copy just fine in a move context.

If you want your code to be high performance, then tailor your move constructor and move assignment to be as fast as possible. Good move members will be blazingly fast, and you should be estimating their speed by counting loads, stores and branches. If you can write something with 4 load/stores instead of 8, do it! If you can write something with no branches instead of 1, do it!

When you (or your client) put your class into a std::vector, a lot of moves can get generated on your type. Even if your move is lightning fast at 8 loads/stores, if you can make it twice as fast, or even 50% faster with only 4 or 6 loads/stores, imho that is time well spent.

Personally I'm sick of seeing waiting cursors and am willing to donate an extra 5 minutes to writing my code and know that it is as fast as possible.

If you're still not convinced this is worth it, write it both ways and then examine the generated assembly at full optimization. Who knows, your compiler just might be smart enough to optimize away extra loads and stores for you. But by this time you've already invested more time than if you had just written an optimized move constructor in the first place.