The rvalue reference is proposed by C++11 in order to realize move semantic and perfect forwarding.
One, left value and right value
The traditional C++ quotation (that is, lvalue reference) makes the identifier associated with the lvalue.
Left value: an expression that represents data, such as a variable name or dereferenced pointer, the program can obtain its address.
C++11 adds rvalue references, which are represented by &&.
Right value: It can appear on the right side of the assignment expression, but the value of the address operator cannot be applied to it.
A convenient way to distinguish between lvalues and rvalues:
See if you can take the address of the expression, if it can, it is an lvalue, otherwise it is an rvalue .
Two, lvalue reference and rvalue reference
Lvalue reference: the reference in C++98,
For example:
int a = 10;
int& refA = a; // refA是a的别名, 修改refA就是修改a, a是左值,左移是左值引用
int& b = 1; //编译错误! 1是右值,不能够使用左值引用
Here int& refA = a;
The compiler finds it is an lvalue reference,
The following conversion will be done automatically:
int& refA -> int* const refA = &a;If required refA = 20;
The compiler will automatically convert to:
*refA = 20;
refA and a both manipulate the same block address.
The essence of an lvalue reference is a pointer constant.
The symbol used for rvalue references is &&,
Such as:
inline double f(double tf) {return 5.0*(tf-32.0)/9.0};
using namespace std;
int main()
{
double tc = 21.5;
double&& rd1 = 7.07;
double&& rd2 = 1.8*tc + 32.0;
double&& rd3 = f(rd2);
cout<<"tc value and address:"<<tc<<","<<&tc<<endl;
cout<<"rd1 value and address:"<<rd1<<","<<&rd1<<endl;
cout<<"rd2 value and address:"<<rd2<<","<<&rd2<<endl;
cout<<"rd3 value and address:"<<rd3<<","<<&rd3<<endl;
cin.get();
return 0;
}
result:
Note: The type of rd1 here is an rvalue reference type (double &&
), but if you distinguish it from the perspective of lvalue and rvalue, it is actually an lvalue. Because it can be addressed, and it also has a name, which is a named rvalue.