Lvalue and rvalue references Detailed

Explanation

Guming Si Yee

Left reference value is a reference value is left to the left alias value

Rvalue reference is to the right reference value is the value to the right alias

When changing the value of an alias is changed accordingly

So how to distinguish what is left and what is the value of the right value of it?

Lvalue Rvalue
The amount of specific addresses in memory Amount register

Since the variable amount of application will open up an address value left in memory, also called specific address

such as:

int a=10; //a 是左值 double b=1.3; //b 是左值 左值引用 int & Ta=a; //引用左值 故 是一个左值引用 double & Tb=b; //引用左值 故是一个左值引用 

Then the amount of what it registers what is it?

Popular to say the amount is calculated value of the register, the function returns the temporary variables or constants
of which have one thing in common: both can not take its address

such as:

'a'  是常量  故为右值
3    是常量  故为右值
1+3 运算会将 1+3 的结果保存至 寄存器 此时并不在特定的内存位置 故 该值为右值 是临时变量 int add() { return 0; } //该函数返回的值并不会保存在内存中 仅出现在临时量中 语句执行完毕后 该临时量被销毁 右值引用 char && a="a"; //常量 int && b=1+3; //临时变量 int&& c= add(); //函数引用 

Key:

The reference value can not be left to the right value

Must not be left to the right value of the reference value

Lvalue reference to an instance

#include<iostream> using namespace std; int main(void) { int a=10; //左值 int & In_a=a; //左值引用 cout<<"Old:"<<In_a<<endl; In_a=2; //改变别名 cout<<"New:"<<In_a<<endl; return 0; } 

result:

 


When the value of the left and right reference value:

 

Rvalue references examples

#include<iostream> using namespace std; int add() { return 0; } //返回常量 0 int fun(int&& f) //形参为右值引用 { cout << f << endl; return 1; } //返回常量 1 int main(void) { 'a'; //常量 'a' 3; //常量 3 1 + 3; //寄存器量 1+3结果 4 //使用右值引用 char && Char_a = 'a'; cout << "'a':" << Char_a << endl; int && Int_a = 3; cout << "3:" << Int_a << endl; int && Int_b = 1 + 3; cout << "1+3:" << Int_b << endl; int &&Int_c = add(); cout << "add()return 0:" << Int_c << endl; int && Int_d = fun(3); //输出3 cout << "fun() 3:" << Int_d << endl; return 0; } 

result

 


When the right value of the reference value left:
Here Insert Picture Description

Value cited above rules and use the left and right values

But template references are different
results because the type of optimization is automatically pushed to the back of

Such as:

#include<iostream> using namespace std; template<typename T> //函数模板 void fun(T&& f) //兼容 左值引用 和右值引用 { cout << f << endl; } int main(void) { int a = 10; fun(a); fun(3); //兼容 左值引用 和右值引用 return 0; } 

result
Here Insert Picture Description

But priority will match the value we provide left lvalue reference version reference version

Guess you like

Origin www.cnblogs.com/tinaluo/p/11440984.html