为什么 std::vector 和 std::array 的 C++ initializer_list 行为不同?

2022-01-07 00:00:00 c++ c++11 stl

代码:

std::vector<int> x{1,2,3,4};
std::array<int, 4> y{{1,2,3,4}};

为什么 std::array 需要双花括号?

Why do I need double curly braces for std::array?

推荐答案

std::array 是一个聚合:它没有任何用户声明的构造函数,甚至没有一个采用 std::initializer_list.使用大括号进行初始化是使用聚合初始化来执行的,这是从 C 继承的 C++ 特性.

std::array<T, N> is an aggregate: it doesn't have any user-declared constructors, not even one taking a std::initializer_list. Initialization using braces is performed using aggregate initialization, a feature of C++ that was inherited from C.

聚合初始化的旧风格"使用=:

The "old style" of aggregate initialization uses the =:

std::array<int, 4> y = { { 1, 2, 3, 4 } };

使用这种老式的聚合初始化,额外的大括号可能会被省略,所以这相当于:

With this old style of aggregate initialization, extra braces may be elided, so this is equivalent to:

std::array<int, 4> y = { 1, 2, 3, 4 };

然而,这些额外的大括号只能在T x = { a };"形式的声明中被省略(C++11 §8.5.1/11),也就是说,当使用旧样式 = 时.这条允许大括号省略的规则不适用于直接列表初始化.这里的脚注是:在列表初始化的其他用途中不能省略大括号."

However, these extra braces may only be elided "in a declaration of the form T x = { a };" (C++11 §8.5.1/11), that is, when the old style = is used . This rule allowing brace elision does not apply for direct list initialization. A footnote here reads: "Braces cannot be elided in other uses of list-initialization."

有关于此限制的缺陷报告:CWG 缺陷 #1270.如果提议的决议获得通过,则其他形式的列表初始化将允许省略大括号,以下内容将是良构的:

There is a defect report concerning this restriction: CWG defect #1270. If the proposed resolution is adopted, brace elision will be allowed for other forms of list initialization, and the following will be well-formed:

std::array<int, 4> y{ 1, 2, 3, 4 };

(感谢 Ville Voutilainen 找到缺陷报告.)

(Hat tip to Ville Voutilainen for finding the defect report.)

相关文章