我尝试使用不同的选项在 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/