C++ References


An r-value reference can be explicitly bound to an r-value. An r-value is an unnamed object; a temporary object, in other words, so called right value because it can only appear on the right side of an equation.


The r-value reference, while not in and of itself particularly useful (much like the l-value reference, actually), can be used to overload functions to respond differently depending on whether a parameter is an l-value or an r-value type, giving different behaviour in each case.

There are (as always) some complications. The compiler only favours r-value reference overloads for modifiable r-values; for constant r-values it always prefers constant l-value references (for backward compatibility). This means overloading functions for const T&& has no real application.

As we can now distinguish between l-value and r-value objects we can overload the constructor (and, later, assignment operator) to support resource pilfering.

Move constructor

The move constructor is an overload of a class constructor that takes an r-value reference as a parameter. That is, the compiler can determine that the object used as the source is going out of scope in the near future and so we can pilfer its resources to construct the new object. The basic process is to take ownership of all the source object&s attributes then leave it in an empty state.

What constitutes empty will obviously vary from class to class; but basically it means leaving the object in such a state that its destructor will not fail or throw an exception.