[C++11] decltype的使用

C++语言 码拜 8年前 (2016-09-12) 1385次浏览
int i =4;
decltype(++i) var9 = i;               //var9:int&            ++i返回i的左值
decltype(i++) var10;                 //var10:int             i++返回右值
问题:
为什么上面的++i和i++返回的不一样呢?
解决方案

10

The operand of prefix ++ is modified by adding 1, or set to true if it is bool (this use is deprecated). The
operand shall be a modifiable lvalue. The type of the operand shall be an arithmetic type or a pointer to
a completely-defined object type. The result is the updated operand; it is an lvalue.
The value of a postfix ++ expression is the value of its operand. [Note: the value obtained is a copy of
the original value —end note ] The operand shall be a modifiable lvalue. The type of the operand shall be
an arithmetic type or a pointer to a complete object type. The value of the operand object is modified by
adding 1 to it, unless the object is of type bool, in which case it is set to true. [Note: this use is deprecated,
see Annex D. —end note ] The value computation of the ++ expression is sequenced before the modification
of the operand object. With respect to an indeterminately-sequenced function call, the operation of postfix
++ is a single evaluation. [Note: Therefore, a function call shall not intervene between the lvalue-to-rvalue
conversion and the side effect associated with any single postfix ++ operator. —end note ] The result is a
prvalue

10

续1楼:
4 For an expression e, the type denoted by decltype(e) is defined as follows:
(4.1) — if e is an unparenthesized id-expression or an unparenthesized class member access (5.2.5), decltype(e)
is the type of the entity named by e. If there is no such entity, or if e names a set of overloaded functions, the program is ill-formed;
(4.2) — otherwise, if e is an xvalue, decltype(e) is T&&, where T is the type of e;
(4.3) — otherwise, if e is an lvalue, decltype(e) is T&, where T is the type of e;
(4.4) — otherwise, decltype(e) is the type of e.
decltype(++i) var9 = i;               //var9:int&            ++i返回i的左值, (4.3)
decltype(i++) var10;                 //var10:int             i++返回右值, (4.4) , prvalue 不是 xvalue 。

10

++i,返回的是自身加一的结果,
i++,返回的是自身加一之前的临时值,

20

对于 decltype
b) if the value category of expression is lvalue, then decltype yields T&;
http://en.cppreference.com/w/cpp/language/decltype

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明[C++11] decltype的使用
喜欢 (0)
[1034331897@qq.com]
分享 (0)