C++中左值和右值的定义

摘录自语言作者原书原文
之前看了不少关于C++的书籍,其中对于左值、右值的解释出现了很多角度,但总觉得差点意思,就是那种总有些想不太明白的地方,所以我还是去读了原文,我觉得原文讲的还是很清晰的,这里摘抄一段和大家共享,其实算不上原创,但的确文章类型只有原创、转载、翻译三个选项,因此还是厚着脸皮选了原创,望体谅。原文如下

Lvalues and Rvalues
To complement the notion of an lvalue, we have the notion of an rvalue. Roughly, rvalue means ‘‘a
value that is not an lvalue,’’ such as a temporary value (e.g., the value returned by a function).
If you need to be more technical (say, because you want to read the ISO C++ standard), you
need a more refined view of lvalue and rvalue. There are two properties that matter for an object
when it comes to addressing, copying, and moving:
• Has identity: The program has the name of, pointer to, or reference to the object so that it is
possible to determine if two objects are the same, whether the value of the object has
changed, etc.
• Movable: The object may be moved from (i.e., we are allowed to move its value to another
location and leave the object in a valid but unspecified state, rather than copying; §17.5).
It turns out that three of the four possible combinations of those two properties are needed to precisely describe the C++ language rules (we have no need for objects that do not have identity and cannot be moved). Using ‘‘m for movable’’ and ‘‘i for has identity,’’ we can represent this classification of expressions graphically:

So, a classical lvalue is something that has identity and cannot be moved (because we could examine it after a move), and a classical rvalue is anything that we are allowed to move from. The other
alternatives are prvalue (‘‘pure rvalue’’), glvalue (‘‘generalized lvalue’’), and xvalue (‘‘x’’ for ‘‘extraordinary’’ or ‘‘expert only’’; the suggestions for the meaning of this ‘‘x’’ have been quite imaginative). For example:
void f(vector& vs)
{
vector& v2 = std::move(vs); // move vs to v2
// …
}
Here, std::move(vs) is an xvalue: it clearly has identity (we can refer to it as vs), but we have explicitly given permission for it to be moved from by calling std::move() (§3.3.2, §35.5.1).
For practical programming, thinking in terms of rvalue and lvalue is usually sufficient. Note
that every expression is either an lvalue or an rvalue, but not both.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值