您的位置:首页 > 其它

表达式左值右值

2015-09-17 19:10 453 查看
  左值右值是表达式的属性,该属性称为 value category。按该属性分类,每一个表达式属于下列之一:

lvalue

left value,传统意义上的左值

xvalue

expiring value, x值,指通过“右值引用”产生的对象

prvalue

pure rvalue,纯右值,传统意义上的右值(?)

  而 xvalue 和其他两个类型分别复合,构成:

lvalue + xvalue = glvalue

general lvalue,泛左值

xvalue + prvalue = rvalue

右值

1.区分

  ++x 与 x++ 假定x的定义为 int x=0;,那么前者是 lvalue,后者是rvalue。前者修改自身值,并返回自身;后者先创建一个临时对像,为其赋值,而后修改x的值,最后返回临时对像。区分表达式的左右值属性有一个简便方法:若可对表达式用 & 符取址,则为左值,否则为右值。比如

&obj , &*ptr , &ptr[index] , &++x

有效

&1729 , &(x + y) , &std::string("meow"), &x++

无效

  对于函数调用,根绝返回值类型不同,可以是lvalue、xvalue、prvalue:

The result of calling a function whose return type is an lvalue reference is an lvalue

The result of calling a function whose return type is an rvalue reference is an xvalue.

The result of calling a function whose return type is not a reference is a prvalue.

2.const vs non-const

  左值右值表达式都可以是constnon-const。比如,变量和函数的定义为:

template <class T> int f(T&&);
template <class T> int g(const T&&);
int i;
int n1 = f(i); // calls f<int&>(int&)
int n2 = f(0); // calls f<int>(int&&)
int n3 = g(i); // error: would call g<int>(const int&&), which
// would bind an rvalue reference to an lvalue


View Code
 也就是前面提到的


template <typename Type> void Swap(Type&& sb1, Type&& sb2)


  参数推导后

void Swap<int&>(int& sb1, int& sb1)


7.参考

/article/2399272.html

http://blog.csdn.net/hikaliv/article/details/4541429

http://topic.csdn.net/u/20090706/16/514af7e1-ad20-4ea3-bdf0-bfe6d34d9814.html

http://www.artima.com/cppsource/rvalue.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: