c++ - GCC 的 decltype(auto) 不符合标准?

标签 c++ gcc clang auto decltype

我尝试使用不同的选项在 GCC 8.2 下编译此 C++ 代码,它总是成功,不产生任何警告并输出 true:

int && a = 123;
decltype(auto) b = a;

std::cout << std::boolalpha << std::is_same<decltype(b), int&>::value;

同时,相同的代码不会在 Clang 中编译,如果我对标准的理解是正确的,那就是符合标准的行为。

decltype 上的 cppreference:

If the argument is an unparenthesized id-expression or an unparenthesized class member access expression, then decltype yields the type of the entity named by this expression.

decltype(auto) 上的 cppreference:

If the declared type of the variable is decltype(auto), the keyword auto is replaced with the expression (or expression list) of its initializer, and the actual type is deduced using the rules for decltype.

因此,decltype(auto) 应该产生 int&&。由于 a 是左值,它不应绑定(bind)到 b,从而导致编译错误。

那么 GCC 是否不符合标准,还是我遗漏了什么?

最佳答案

你的推理很有道理。我想我看到了 GCC 的问题。

decltype(auto) 的措辞表示 auto 在初始化程序中被替换为 expression。根据 GCC,这意味着您的代码不等同于

decltype(a) b = a;

而是相当于

decltype((a)) b = a;

但这是错误的。初始值设定项 “未加括号的 id 表达式”,因此 [dcl.type.simple] 中用于未加括号的 id 表达式的规则应该正常应用。 b的类型需要推导为int&&


作为@Aconcagua居然能挖出来,这是一个known GCC bug .

关于c++ - GCC 的 decltype(auto) 不符合标准?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53358751/

相关文章:

python - Python 和 libstdc++ 的动态库问题

c - 堆栈分配、填充和对齐

linux - 了解事件是否发生(运行 gtk_dialog_run() 时)

c++ - 如果函数在匿名命名空间中声明,是否可以在全局命名空间中定义?

c++ - 完美转发对象数组

c++ - 在 Mac 上编写 C++ 程序的最佳方式是什么?

c++ - 将名称添加到 C++ 中的数组位置

c++ - 将 libnoise 库链接到 Visual Studio 2010 中的项目时遇到问题

c++ - 摆脱断言中未使用值的警告

c++ - nullptr_t 是默认的可构造类型吗?