What is R-Value reference that is about to come in next c++ standard?
-
21-08-2019 - |
Question
What is R-Value reference that is about to come in next c++ standard?
Solution 3
Here is a really long article from Stephan T. Lavavej
OTHER TIPS
Take a look at Why are C++0x rvalue reference not the default? , which explains their practical use fairly well.
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.