views:

265

answers:

5

What is R-Value reference that is about to come in next c++ standard?

+3  A: 

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.

1800 INFORMATION
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
+2  A: 

Take a look at http://stackoverflow.com/questions/844241/why-are-c0x-rvalue-reference-not-the-default , which explains their practical use fairly well.

Matthew Flaschen
A: 

Lots of detailed answers already here:

http://stackoverflow.com/questions/844241/why-are-c0x-rvalue-reference-not-the-default

(The question isn't worded the same but turned out to be the same question: what's the point of adding the new kind of references?)

Daniel Earwicker
+1  A: 

Here is a really long article from Stephan T. Lavavej

yesraaj