带有 char 数组的 C++ 结构以不寻常的方式初始化为零
C++ struct with char arrays initialize to zero in unusual way
遇到了一段不常见的 c++ 初始化代码,似乎可以很好地处理以下...
struct sfoobar { char bar[10]; char foo[10]; };
...
sfoobar x { 0 };
这是将这些字符数组初始化为零的可接受方法吗?
这在 C++ 中有效。由于效果 sfoobar x { 0 };
会将 x.bar
和 x.foo
的所有元素初始化为 0
.
根据aggregate initialization的规则,嵌套初始化列表的大括号可以省略,
the braces around the nested initializer lists may be elided (omitted), in which case as many initializer clauses as necessary are used to initialize every member or element of the corresponding subaggregate, and the subsequent initializer clauses are used to initialize the following members of the object.
则sfoobar x { 0 };
表示将x.bar
的第1个元素初始化为0
,
If the number of initializer clauses is less than the number of members and bases (since C++17)
or initializer list is completely empty, the remaining members and bases (since C++17)
are initialized by their default initializers, if provided in the class definition, and otherwise (since C++14)
by empty lists, in accordance with the usual list-initialization rules (which performs value-initialization for non-class types and non-aggregate classes with default constructors, and aggregate initialization for aggregates).
所以所有剩余的元素,包括x.bar
的第2到第10个元素和x.foo
的所有元素也将值初始化为0
。
遇到了一段不常见的 c++ 初始化代码,似乎可以很好地处理以下...
struct sfoobar { char bar[10]; char foo[10]; };
...
sfoobar x { 0 };
这是将这些字符数组初始化为零的可接受方法吗?
这在 C++ 中有效。由于效果 sfoobar x { 0 };
会将 x.bar
和 x.foo
的所有元素初始化为 0
.
根据aggregate initialization的规则,嵌套初始化列表的大括号可以省略,
the braces around the nested initializer lists may be elided (omitted), in which case as many initializer clauses as necessary are used to initialize every member or element of the corresponding subaggregate, and the subsequent initializer clauses are used to initialize the following members of the object.
则sfoobar x { 0 };
表示将x.bar
的第1个元素初始化为0
,
If the number of initializer clauses is less than the number of members
and bases (since C++17)
or initializer list is completely empty, the remaining membersand bases (since C++17)
are initializedby their default initializers, if provided in the class definition, and otherwise (since C++14)
by empty lists, in accordance with the usual list-initialization rules (which performs value-initialization for non-class types and non-aggregate classes with default constructors, and aggregate initialization for aggregates).
所以所有剩余的元素,包括x.bar
的第2到第10个元素和x.foo
的所有元素也将值初始化为0
。