🌐 中文 English
What are lvalues and rvalues, referencing the differences between C++ lvalue and rvalue references
Differences Between Lvalues and Rvalues
An lvalue is an expression that can appear on the left side of an assignment statement, while an rvalue is an expression that can only appear on the right side of an assignment statement.
1
2
3
a = 10; // 10 is an rvalue, a is an lvalue
vector<int> v;
v = vector<int>(10, 0); // vector<int>(10, 0) is an rvalue, v is an lvalue
Simply put, lvalues can be assigned to, while rvalues cannot be assigned to (i.e., the left side of = is an lvalue, the right side is an rvalue).
Differences Between Lvalue References and Rvalue References (Rvalue references were introduced in C++11)
Understanding the difference between lvalues and rvalues, we can now explore the differences between lvalue references and rvalue references. As the names suggest, an lvalue reference binds to an lvalue, while an rvalue reference binds to an rvalue.
The syntax for lvalue references: type&, and for rvalue references: type&&. Examples are as follows:
1
2
3
4
5
6
7
int a = 10; // assignment
int &b = a; // lvalue reference
int &&c = 10; // rvalue reference
vector<int> v = vector<int>(10, 0); // assignment
vector<int> &v1 = v; // lvalue reference
vector<int> &&v2 = vector<int>(10, 0); // rvalue reference
Differences Between const Lvalue References and const Rvalue References
The difference between const lvalue references and rvalue references is that const lvalue references can bind to rvalues, while const rvalue references cannot bind to lvalues.
1
2
3
4
int a = 10;
const int&& b = a; // error
const int& c = a; // lvalue
const int& d = 10; // rvalue
Summary
- The difference between lvalue references and rvalue references is that lvalue references can bind to lvalues, while rvalue references can bind to rvalues.
- The difference between const lvalue references and rvalue references is that const lvalue references can bind to rvalues, while const rvalue references cannot bind to lvalues.