Daily C++11: How to write move constructors

When I passed to the next matter regarding C++11 in my series, I realized that I didn’t give an example on how to write move constructors in the real world. For anyone who works actively with C++11 it’s obvious, but for people like me that want to find out about the new standard, it would be instrumental to actually see some example. I hope it’ll be clear enough:

The line I would like to draw attention to is what happens in the move constructor. After the move constructor steals the content of the object that it moves from, it sets the pointer to NULL. Another idea would be to set a flag to indicate that the data has been moved, and the destructor should first check that flag – the choice would be yours.

I also have included an example implementation for the assignment operator. Two things to note: first we check to make sure we don’t assign from our own object (that would be really really bad, because first we would free the data). Secondly, we free existing data, so that we don’t have a memory leak.

If you replace the move constructor with the default, the above example WILL crash – this is because destructors are STILL called for objects moved from. This detail is important, and you have to make sure that you define the destructor correctly.

Note that there will be no implicit move constructor. If you remove the definition of the move constructor, the copy constructor will be used instead. The rules for copy constructor stay the same, obviously.

Good luck writing your future code!

Comments are closed.