gcc 8 和 clang 7 不接受下面的代码,它应该默认构造一个 unsigned int
类型的临时文件:
unsigned int ui = unsigned int{};
clang 7报错如
<source>:6:22: error: expected primary-expression before 'unsigned'
Visual C++ 2015 和 2017 接受这一点。
显然,这适用于 int
或任何可默认构造的类类型。
这是正确的 C++14 代码吗(在那种情况下是 clang 和 gcc 的错误)?如果不是,为什么不呢?除无符号类型外,哪些类型会受到相同的限制?
最佳答案
new_type { expression-list(optional) }
like unsigned int{}
符合 explicit type conversion 的语法, 只允许单字类型名称。
A single-word type name followed by a braced-init-list is a prvalue of the specified type
designating a temporary (until C++17)
whose result object is (since C++17)
direct-list-initialized with the specified braced-init-list.
请注意,unsigned int
不是单字类型名称,而 int
是。所以 int {}
工作正常。
这对于函数式转换表达式也是一样的,
The functional cast expression consists of a simple type specifier or a typedef specifier (in other words, a single-word type name:
unsigned int(expression)
orint*(expression)
are not valid),
作为解决方法,您可以应用类型别名,例如
using type = unsigned int;
type ui = type{};
关于c++ - 花括号初始化列表和无符号类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53336344/