lvalue,rvalue,xvalue,gvalue,prvalue到底怎么区分

右值引用其实就是一种对外声明,我将接管传入的参数的权利,比如内存空间,原拥有者将丧失对应权利,当然这种接管是通过具体代码来实现的,并不是声明为右值引用,编译器就自动实现接管功能。

右值引用类型既可以被当作左值也可以被当作右值,判断的标准是,如果它有名字,那就是左值,否则就是右值。

在C11中,开始大量使用lvalue,rvalue,xvalue,glvalue,prvalue,已经由此带来的左值引用,右值引用。glvalue,rvalue属于组合后产生的概念。这几个名字的关系如下图所示:

Taxonomy

T是一个具体类型:

  1. 左值引用, 使用 T&, 只能绑定左值
  2. 右值引用, 使用 T&&, 只能绑定右值
  3. 常量左值, 使用 const T&, 既可以绑定左值又可以绑定右值
  4. 已命名的右值引用,编译器会认为是个左值
  5. 编译器有返回值优化,但不要过于依赖

c++11增加了引用折叠的规则,总结如下:

  1. 所有的右值引用叠加到右值引用上仍然使一个右值引用。
  2. 所有的其他引用类型之间的叠加都将变成左值引用。

个人理解,在C11里边,上述左值,右值的概念已经进行了推广,不再是最初的意义,不能通过能否放在操作符的左端或右端作为分类的目的。

上述分类的引入,更多的是为了move语法的使用,使得move相关描述和使用更准确,以免误解或误用。

上边虽然有五种类别,但关键还是lvalue, prvalue, xvalue怎么区分,这方面有很多人写文章讨论,但是鲜有人给出lvalue, prvalue, xvalue明确的定义,只是给出了一个大致的分类方法或技巧,感觉这些方法还是大部分场景有效,有时未必有效。

 

今天看到到一个分类方法:

1)如果有标识符,且不可移动,则被称为lvalue

2)如果有标识符,且可移动,被称为xvalue

3)如果没有标识符,且可移动,称为prvalue

 

这样看起来很容易区分,但是问题来了,怎么判断是否可移动呢?

 

在stackoverfow上,看到有人给出了lvalue, prvalue, xvalue的明确定义,但是没说这个定义是从哪里来的:

http://stackoverflow.com/questions/3601602/what-are-rvalues-lvalues-xvalues-glvalues-and-prvalues

 

 

lvalues

 

The expression E belongs to the lvalue category if and only if E refers to an entity that ALREADY has had an identity (address, name or alias) that makes it accessible outside of E.

xvalues

The expression E belongs to the xvalue category if and only if it is

— the result of calling a function, whether implicitly or explicitly, whose return type is an rvalue reference to the type of object being returned, or

— a cast to an rvalue reference to object type, or

— a class member access expression designating a non-static data member of non-reference type in which the object expression is an xvalue, or

 

— a pointer-to-member expression in which the first operand is an xvalue and the second operand is a pointer to data member.

Note that the effect of the rules above is that named rvalue references to objects are treated as lvalues and unnamed rvalue references to objects are treated as xvalues; rvalue references to functions are treated as lvalues whether named or not.

 

 

prvalues

 

The expression E belongs to the prvalue category if and only if E belongs neither to the lvalue nor to the xvalue category.

相对而言,上述定义可能更清晰一点。
 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值