What is R-Value reference that is about to come in next c++ standard?
-
I can see this question one day becoming the C++ equivalent of "How do I join a list of strings together in C#?"), i.e. asked and answered every couple of days! – Daniel Earwicker May 11 '09 at 07:15
4 Answers
It allows you to distinguish between code that has called you passing a reference to an r-value or an l-value. For example:
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 an r-value reference, we can allow to pass in references to temporaries 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 are wanting to pass the return value of a function that creates an object to another function which 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 the copy constructor, but it is defined to take an r-value reference rather than an l-value (const) reference. It is allowed to use r-value semantics to move the data out of the temporary created in create_vector
and push them into the argument to consume_vector
without doing an expensive copy of all of the data in the vector.

- 131,367
- 29
- 160
- 239
-
create_vector would return by value, not by rvalue reference (this would be a reference to a temporary). Note that value return types are already rvalues. – James Hopkin May 12 '09 at 19:05
Take a look at Why are C++0x rvalue reference not the default? , which explains their practical use fairly well.

- 1
- 1

- 278,309
- 50
- 514
- 539
-
1Watch out though, he mentions in a later video lecture that the article was based on rvalue references v1, and the rules changed subsequently to "v2". In the original version rvalue references would bind to lvalues, but then the committee changed the rules. Just a warning. – woolstar Dec 07 '13 at 04:21