What is the R-Value reference that should come in the next C ++ standard?
This allows you to distinguish between the code that called you by passing a reference to an r-value or an l-value. For instance:
void foo(int &x);
foo(1); // we are calling here with the r-value 1. This would be a compilation error
int x=1;
foo(x); // we are calling here with the l-value x. This is ok
By using the r-value reference, we can allow passing references to temporary sections, such as in the first example above:
void foo(int &&x); // x is an r-value reference
foo(1); // will call the r-value version
int x=1;
foo(x); // will call the l-value version
This is more interesting when we want to pass the return value to a function that creates an object to another function that uses that object.
std::vector create_vector(); // creates and returns a new vector
void consume_vector(std::vector &&vec); // consumes the vector
consume_vector(create_vector()); // only the "move constructor" needs to be invoked, if one is defined
The move constructor acts like a copy constructor, but it is defined as an r-value reference, not an l-value (const) reference. It is allowed to use r-value semantics to move data from a temporary created to create_vector
and insert it into an argument consume_vector
without making an expensive copy of all the data in the vector.
a source to share
Take a look at Why is C ++ 0x rvalue reference not default? , which explains their practical use quite well.
a source to share