c++ - std::array 初始化中的大括号省略

标签 c++ c++11 language-lawyer list-initialization aggregate-initialization

假设有一个 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/

相关文章:

c++ - 在 MFC 应用程序中监听 UDP 或切换到 TCP

c++ - 模拟 const 值以进行测试

C99 "processor time"的定义

c++ - 如何将 QMainWindow 设置为模式窗口?

c++ - 连接Broadcom设备解析云

c++ - 如何从由 google HEAPPROFILER 创建的 .heap 文件生成图表

c++ - 代码中奇怪的 constexpr 参数

c++ - 移动指针类型的构造函数?

c++ - 向前声明类模板显式/部分特化有什么意义?

c++ - 定义 uint64_t 常量的最佳/正确方法