The difference between lvalue reference and rvalue reference in C++

01 What are lvalues ​​and rvalues?

  • Left value: It is a variable with a certain memory address and a name, which can be assigned and used in multiple statements;
  • Rvalue: Temporary variable without a name, cannot be assigned, and can only appear in a statement, such as literal constants and temporary variables .

02 How to distinguish between lvalue and rvalue?

See if you can address the expression

能否用“取地址&”运算符获得对象的内存地址。
对于临时对象,它可以存储于寄存器中,所以是没办法用“取地址&”运算符;
对于常量,它可能被编码到机器指令的“立即数”中,所以是没办法用“取地址&”运算符;
这也是C/C++标准的规定。

Returns the value of the left expression: 返回左值引用的函数、赋值、下标、解引用、前置递增/递减运算符.
Returns the value of the right expression: 返回非引用类型的函数、算术、关系、位、后置递增/递减运算符.
For example:

int a = 5;
int b = 6;
int *ptr = &a; 
vector v1; 
string str1 = "hello " ;
string str2 = "world" ;
const int &m = 1 ;

a+b//临时对象
a++//右值,是先取出持久对象a的一份拷贝,再使持久对象a的值加1,最后返回那份拷贝,而那份拷贝是临时对象(不可以对其取地址),故其是右值。
++a//左值,使持久对象a的值加1,并返回那个持久对象a本身(可以对其取地址),故其是左值。
v1[0]//调用了重载的[]操作符,而[]操作符返回的是一个int &,为持久对象(可以对其取地址)是左值。
string("hello")//临时对象(不可以对其取地址),是右值;
str1+str2//调用了+操作符,而+操作符返回的是一个string(不可以对其取地址),故其为右值;
str1//左值
*p//左值

03 Lvalue references and rvalue references

C ++ 11 introduced rvalue references, c ++ 11 in a reference value & represents a left, a right && with reference values.

int i = 2;//左值
int &a = i; //左值引用

int &&a = 10; //右值引用

According to different modifiers, lvalue references can be divided into: non-const lvalue, const lvalue ; rvalue reference can be divided into: non-const rvalue, const rvalue .

int i = 10;//非const左值
const int j = 20;

//非const左值引用
int &a = i;//非const左值引用 绑定到 非const左值,编译通过
int &a = j;//非const左值引用 绑定到 const左值,编译失败
int &a = 5;//非const左值引用 绑定到 右值,编译失败

//const左值引用
const int &b = i;//const左值引用 绑定到 非const左值,编译通过
const int &b = j;//const左值引用 绑定到 const左值,编译通过
const int &b = 5;//const左值引用 绑定到 右值,编译通过

//非const右值引用
int &&c = 30;//非const右值引用 绑定到 右值,编译通过
int &&c = i;//非const右值引用 绑定到 非const左值,编译失败(不能将一个右值引用绑定到左值上)

//const右值引用
const int &&d = 40;//const右值引用 绑定到 右值,编译通过
const int &&d = c;//const右值引用 绑定到 非常量右值,编译通过
  • Non-constant lvalue references can only be bound to non-constant lvalues
  • Non-constant rvalue references can only be bound to non-constant rvalues

04 Summary

  • Non-constant lvalue references can only be bound to 非常量左值, but not to constant lvalues, non-constant rvalues, and constant rvalues;
  • Constant lvalue references can be bound to const左值、非const左值、const右值、非const右值.
  • Non-const rvalue references can only be bound to 非const右值;
  • const rvalue references can be bound to const右值和非const右值.

Reference documents

Guess you like

Origin blog.csdn.net/qq_41363459/article/details/113862371