假设有一个 std::array
需要初始化。用双括号也没关系:
std::array<int, 2> x = {{0, 1}};
std::array<int, 2> x{{0, 1}};
在良好的旧聚合初始化中使用单大括号也是可以的,因为大括号省略会处理丢失的大括号:
std::array<int, 2> x = {0, 1};
但是,可以使用带有单括号的列表初始化吗? GCC 接受它,Clang 以“在使用直接列表初始化时不能省略子对象初始化周围的大括号”来拒绝它。
std::array<int, 2> x{0, 1};
标准中唯一提到大括号省略的部分是 8.5.1/12,它说:
All implicit type conversions (Clause 4) are considered when initializing the aggregate member with an assignment-expression. If the assignment-expression can initialize a member, the member is initialized. Otherwise, if the member is itself a subaggregate, brace elision is assumed and the assignment-expression is considered for the initialization of the first member of the subaggregate.
8.5.1 是关于聚合初始化的,所以这应该意味着 Clang 拒绝是正确的,对吧?没那么快。 8.5.4/3 说:
List-initialization of an object or reference of type T is defined as follows:
[…]
— Otherwise, if T is an aggregate, aggregate initialization is performed (8.5.1).
我认为这意味着与聚合初始化完全相同的规则,包括大括号省略、应用,这意味着 GCC 可以正确接受。
我承认,措辞不是特别清楚。那么,哪个编译器在处理第三个片段时是正确的?大括号省略是否发生在列表初始化中,还是没有?
最佳答案
大括号省略适用,但不适用于 C++11。在 C++14 中,它们将应用因为 http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1270 .如果幸运的话,Clang 会将其反向移植到他们的 C++11 模式(希望他们会这样做!)。
关于c++ - std::array 初始化中的大括号省略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16985687/