遇到一段不常见的 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.
then sfoobar x { 0 };
表示将x.bar
的第一个元素初始化为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
也是。
关于带有 char 数组的 C++ 结构以不寻常的方式初始化为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49992802/