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.
原文链接: https://www.cnblogs.com/yunpengk/p/12954748.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;
也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/350686
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!