聚合初始化中的大括号很大程度上是可选的,因此您可以编写:
S c_arr[] = {1, 2, 3, 4}; // OK
std::array<S, 2> std_arr = {1, 2, 3, 4}; // OK
但是,如果您添加大括号,则大括号将应用于下一个子对象。不幸的是,当您开始嵌套时,这会导致愚蠢的代码有效,而像您这样的明智代码无效。
std::array<S, 2> std_arr = {{1, 2, 3, 4}}; // OK
std::array<S, 2> std_arr = {1, 2, {3, 4}}; // OK
std::array<S, 2> std_arr = {1, {2}, {3, 4}}; // OK
这些都可以。{1, 2, 3, 4}
是一个有效的初始化程序S[2]
成员std_arr
. {2}
没关系,因为它是尝试初始化int
, and {2}
是一个有效的初始化程序。{3, 4}
被视为初始化程序S
,并且它也适用于此。
std::array<S, 2> std_arr = {{1, 2}, {3, 4}}; // error
这不行,因为{1, 2}
被视为有效的初始化程序S[2]
成员。其余int
子对象初始化为零。
那么你就有了{3, 4}
,但没有更多成员可以初始化。
正如评论中指出的那样,
std::array<S, 2> std_arr = {{{1, 2}, {3, 4}}};
也有效。嵌套的{{1, 2}, {3, 4}}
是一个初始化程序S[2]
成员。这{1, 2}
是第一个的初始化程序S
元素。这{3, 4}
是第二个的初始化程序S
元素。
I'm assuming here that std::array<S, 2>
contains an array member of type S[2]
, which it does on current implementations, and which I believe is likely to become guaranteed, but which has been covered on SO before and is not currently guaranteed.