带有 char 数组的 C++ 结构以不寻常的方式初始化为零

标签 c++ initialization aggregate-initialization

遇到一段不常见的 c++ 初始化代码,似乎可以很好地处理以下...

struct sfoobar { char bar[10]; char foo[10]; };
...
sfoobar x { 0 };

这是将这些字符数组初始化为零的可接受方法吗?

最佳答案

这在 C++ 中有效。作为效果 sfoobar x { 0 }; 会将 x.barx.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 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 也是。

关于带有 char 数组的 C++ 结构以不寻常的方式初始化为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49992802/

相关文章:

c++ - 开发 C++ 编译器错误

c - 初始化大型双数组时出现问题

c++ - 带有大括号初始化的 make_unique

c++ - 如何使用自定义结构初始化 boost::array?

c++ - 关于循环变量优化的标准合规行为是什么?

c++ - 识别字符串中的下一个字符是否大写

C# - 检查变量是否已初始化

c++ 聚合初始化器 g++ 错误?

c++ - 在 c++20 中删除了默认构造函数的聚合初始化

C++使用进程名称获取窗口标题