首页 > 编程语言 > 详细

C++ 11 new feacture (Lvalue and Rvalue)

时间:2020-05-25 09:26:55      阅读:52      评论:0      收藏:0      [点我收藏+]

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!