Left and rvalues and left and rvalue references

1. Lvalues ​​and rvalues

1. What is an lvalue and what is an rvalue?

    Lvalue refers to the content that can appear on the left side of the assignment operator (=), but in fact, lvalue generally has lvalue attributes and rvalue attributes, which can appear not only on the left side of the equal sign, but also on the right side of the equal sign .

    An rvalue refers to something that can only appear on the right side of the assignment operator (=) and cannot be assigned a value. Rvalues ​​only have rvalue properties.

    An lvalue can actually represent an address, an rvalue cannot.

int i = 10;
i = i + 1;

    In the above code, i is an lvalue, which is on the left side of the equal sign in the first statement, and the value 10 is actually an rvalue, on the right side of the equal sign, and it has no concept of address.

Two, lvalue reference and rvalue reference

1. Lvalue reference

    Generally, the references we use are lvalue references, which can be referred to as references for short. A reference is actually an alias for a variable. The following is a simple example of an lvalue reference:

int a = 5;
int& b = a; 
b = 10; // b = 10, a = 10

    In the above example, b is a reference to a, and b can change the value of a, and finally a=10.

2. What is an rvalue reference

    Rvalue reference is a new concept added by C++11. It is a reference to rvalue. The following is a simple usage example:

int&& rightValue = 3;
rightValue = 5; 

    In the above code, rightValue is an rvalue reference, which refers to the value of 3, and the second statement changes the value of rightValue to 5.

3. Some special examples

① Pre-increment and decrement operators, such as ++i, --i, they are lvalue expressions. For example: ++i directly adds 1 to the i variable, and then returns i itself, because i is a variable, so it can be assigned, so it is an lvalue expression.

int i = 5;
(++i) = 10; // i = 20

② Post-increment and decrement operators, such as i++, i--, they are rvalue expressions. For example: i++ first generates a temporary variable to store the value of i, then adds 1 to i, then returns the temporary variable, and then the system releases the temporary variable.

int i = 1;
int&& r1 = i++; // 可以,成功绑定到右值
int& r2 = i++; // 不可以,左值引用不能绑定到右值表达式

Three, std::move function

    The std::move function is a new function in C++11. Its function is to cast an lvalue into an rvalue. The result is that an rvalue reference can be bound to the converted rvalue. Here is an example of simple usage:

void func(int&& arg){}
int i = 10;
int&& ri = std::move(i);
func(ri); // 不可以,std::move(i)返回的是右值,但ri本身是左值
func(std::move(i)); // 可以,因为std::move(i)是右值

Guess you like

Origin blog.csdn.net/hu853712064/article/details/130547260