c++ - 什么是 decltype(0 + 0)?

标签 c++ c++11 rvalue decltype xvalue

(由 an answer 提示。)

鉴于 N3290,§7.1.6.2p4,其中列表项未编号,但为方便起见,此处已编号:

The type denoted by decltype(e) is defined as follows:

  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;
  2. otherwise, if e is an xvalue, decltype(e) is T&&, where T is the type of e;
  3. otherwise, if e is an lvalue, decltype(e) is T&, where T is the type of e;
  4. otherwise, decltype(e) is the type of e.

decltype(0 + 0)指定的类型是什么?

第 1 项不适用,第 2 项可能,但如果不适用,则第 3 项不适用,结果为 4。那么,什么是 xvalue,0 + 0 是 xvalue 吗?

§3.10p1:

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).

我在 §8.3.2 中没有看到任何有用的信息,但我知道“0 + 0”不涉及任何右值引用。文字 0 是一个纯右值,它是“一个不是 xvalue 的右值”(§3.10p1)。我相信“0 + 0”也是一个prvalue。如果这是真的,“decltype(0 + 0)”将是 int(不是 int&&)。

我的解释是否遗漏了什么?这段代码格式正确吗?

decltype(0 + 0) x;  // Not initialized.

代码在 GCC 4.7.0 20110427 和 Clang 2.9(主干 126116)上编译。例如,如果 decltype 指定了 int&& 类型,则格式不正确。

最佳答案

0 + 0 是两个纯右值(n3290 par. 3.10)的表达式,它应用内置 operator+,根据 13.6/12 是 LR operator+(L,R),因此它是一个返回非引用内容的函数。因此,表达式的结果也是纯右值(根据 3.10)。

因此,0 + 0 的结果是纯右值,0 是 int,因此 0 + 0 的结果是 int

关于c++ - 什么是 decltype(0 + 0)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5924870/

相关文章:

c++ - C++调用抽象基类的构造函数

c++ - 如何使用在函数中本地创建的对象而不将其复制到内存中?

c++ - 成员函数调用的对象右值传播

c++ - 遍历右值容器

c++ - C++ 应用程序中的 openssl 错误 SSL_ERROR_SSL

c++ - VC++ 自动说明符假定 vector<bool>::back 的引用限定符

c++ - 使用 boost::assign::list_of 和 boost::variant

c++ - 模板类中 operator* 的尾随返回类型

c++ - 计算一组关系的整数映射的更有效算法

c++ - COM DLL - 覆盖图标