Understanding Rvalue and Lvalue
C++ 11 instroduced rvalue reference.
Lvalue- an object that occupies some identifiable location in memory.
Rvalue- any object that is not a lvalue
Lvalue Example:
int i ; // i is a lvalue, for i‘s address has a unique ID.
int * p = & i ; // i‘s address is identifiable
class dog;
dog d1; // lvalue of user defined type (class),here d1 is a user defined lvalue.
// most variables in c++ code are lvalues.
Rvalue Example:
int x = 2; // 2 is a rvalue
int x = i + 2; // i+ 2 is a rvalue
int* p = &(i+2); // error
i + 2 = 4; // error
2 = i; //error
dog d1;
d1 = dog (); // dog() is rvalue of user defined type
int sum(int x, int y) {return x + y;}
int i = sum(3, 4); // sum (3,4) is a rvalue
//---------------
Rvalue : 2, i + 2, dog(), sum(3,4). x+y;
Lvalue: x, i , d1
//----------------
Reference (or called lvalue reference) !!!
int i;
int& r = i;
int& r = 5; // error
exception: constant lvalue reference can be assign a rvalue
const int& r = 5; (we can think a lvalue temp is created with 5, and temp assignes a rvalue )
int square(int& x) {return x*x};
square(i); //ok
square(40); // error
workaround:
int square(const int & x ) {return x*x;} // square(40) and square(i) work.
Lvalue can be used to create an rvalue;
int i = 1; //i is lvalue
int x = i + 2; //i + 2 is rvalue
int x = i; // i in fact is lvalue, but here it is internnal transformed into rvalue.
Rvalue can be used to create an lvalue
int v[3];
*(v+2) = 4; // v+ 2 is rvalue, *(v+2) is lvalue and can be assigned a value 5.
so the function return can be lvalue, in above example, the function return foo is myglobal(lvalue).
here c is lvalue, but it is declared using const, so it is not modifiable.
so the saying of rvalue not modifiable is only valid for user defined type.
not for the state of dog object.
C++ 11 new feacture (Lvalue and Rvalue)
原文:https://www.cnblogs.com/yunpengk/p/12954748.html