C++ 11 rvalues, lvalues, xvalues, glvalues, prvalues 是什么

来源:互联网 发布:java时间格式hhmmssnnn 编辑:程序博客网 时间:2024/04/29 14:42

实际上对C++中表达式的类型一直有争议,现在以C++11官方文档中给出的解释对原有的和新增的表达式类型进行分析。

节选自FCD (n3092)中关于表达式的一段:

— An lvalue (so called, historically, because lvalues could appear on the left-hand side of an assignment expression) designates a function or an object. [ Example: If E is an expression of pointer type, then *E is an lvalue expression referring to the object or function to which E points. As another example, the result of calling a function whose return type is an lvalue reference is an lvalue. —end example ]

— An xvalue (an “eXpiring” value) also refers to an object, usually near the end of its lifetime (so that its resources may be moved, for example). An xvalue is the result of certain kinds of expressions involving rvalue references (8.3.2). [ Example: The result of calling a function whose return type is an rvalue reference is an xvalue. —end example ]

— A glvalue (“generalized” lvalue) is an lvalue or an xvalue.

— An rvalue (so called, historically, because rvalues could appear on the right-hand side of an assignment expressions) is an xvalue, a temporary object (12.2) or subobject thereof, or a value that is not associated with an object.

— A prvalue (“pure” rvalue) is an rvalue that is not an xvalue. [Example: The result of calling a function whose return type is not a reference is a prvalue. The value of a literal such as 12, 7.3e5, or true is also a prvalue. —end example ]

Every expression belongs to exactly one of the fundamental classifications in this taxonomy: lvalue, xvalue, or prvalue. This property of an expression is called its value category. [ Note: The discussion of each built-in operator in Clause 5 indicates the category of the value it yields and the value categories of the operands it expects. For example, the built-in assignment operators expect that the left operand is an lvalue and that the right operand is a prvalue and yield an lvalue as the result. User-defined operators are functions, and the categories of values they expect and yield are determined by their parameter and return types. —end note

下图简述了这五类表达式的关系:

表达式关系图

lvalues——left/location values

描述

与其翻译为“左值”相比,location values的描述更恰当,即为能取出地址的值。传统的lvalues是能放在赋值符号(=)左边的值,这类值按照需要也可以转化为右值。

举例

函数名、变量名(包括函数指针和具名变量)、返回左值的引用/解引用、函数的引用、前置自增/自减运算符连接的和赋值运算符连接的表达式(++i/--ia=ba+=b)、字符串字面值("abc")。

rvalues——readable values

描述

右值总有一个唯一的可读的值,也就是关于对象的值的表达式。可以只由prvalues、xvalues组成,也可以由他们共同组成。

prvalues——pure right value

描述

纯右值由C语言中只能放在等式右边的值发展而来,即字面值。它的定义常与xvalues混淆,区别参考举例。

举例

例如:3false这样的字面值。

xvalues——expiring value

描述

表达式在执行完赋值任务后就会结束它的生命周期。

举例

1)返回右值引用的函数的调用表达式
2)转换为右值引用的转换函数的调用表达式

std::move()tsatic_cast<X&&>(my_class)

glvalues

是xvalues和lvalues的统称。

0 0
原创粉丝点击