2012-04-26 CPlusPlus11

Moving on

Time to investigate the new move semantics, or at least what I have understood about it! So what is it? It is a way to specify how object state can be moved instead of copied.

Why is that interesting? Well if copying really isn't necessary, since the object just being copied is never going to be used again ever, then we could just move the state instead of making a copy. No more unnecessary copies. Now this is the normal life for temporaries, so called rvalues. They are created, used and sometimes their values are copied to a resulting variable, a lvalue. During this process a move could be deployed instead of a copy so that the lvalue got its state from a rvalue.

More good news is that the compiler knows when this situation occurs. So your code could benefit from this even without a single change. It is something like the return value optimization but there the compiler can even avoid the move altogether and place the result in the right spot from the beginning. As we will see there seems to be some things that complicates this picture a bit.

How does this work then? In order to specify how the move is to be performed we need to create one new type of constructor, the move ctor. This is like the copy-ctor except that it takes a rvalue reference identified by T&&. Note the notation with the double ampersands. A move ctor for class Class would thus be declared like this:

Class(Class&& c)

This ctor defines how the state is moved from the Class object c instance to this object instance. The body of the ctor will of course depend on the implementation of Class. If it has some members that can efficiently be moved then we are in business.

So with this ctor defined everytime a move can be performed this ctor is called. If we had not defined this ctor then the Copy-ctor would be used instead. So there is a fallback solution - how it worked with old versions of the compiler.

The assignment operator can also be defined in a similar way.

Class& operator=(Class&& c)