R-Value references in C++ 11
Firstly, We have to understand the L-values and r-values which are the properties of expression.
All l-values have assigned the memory address whereas r-values are temporary values (they die at the end of the expression they are in).
e.g.
int x = 3;
Here x is l-value and 3 is r-value because x has memory address whereas memory of 3 will die in next statement.
‘l-value reference’ refer to l-value whereas ‘r-value reference’ refer to r-value.
l-value references are declared with one ampersand whereas r-value references with two ampersands.
e.g.
int a = 3;
int & b = a; //b is l-value reference
int && c = 3; //c is r-value reference
int &d = 3; //We get an error:” invalid initialization of non-const reference of ’
//type int& from an rvalue of type int”
Note that const & can bind to r-value e.g. const int &e = 5;
Functions can also be overloaded on the basis of l-value reference and r-value reference.
e.g.
int fun(int & a) {cout <<”lvalue ref”;}
int fun(int &&a) {cout<<”rvalue ref”;}