使用 {0} 初始化结构
initializing struct with {0}
我正在调试一些基本上与此相同的代码:
struct Foo { int a; int b; };
struct Bar { Bar() {} Foo foo{0}; };
当我创建 Bar
的实例时,似乎 a
和 b
都被初始化为零。这有保证吗?我在哪里可以找到规范中的内容?
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 member 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). If a member of a reference type is one of these remaining members, the program is ill-formed.
Foo
没有默认成员初始值设定项 (int b{0};
),因此 b
将通过空列表的列表初始化进行初始化,这意味着非 class 类型:b = int() // = 0
.
我正在调试一些基本上与此相同的代码:
struct Foo { int a; int b; };
struct Bar { Bar() {} Foo foo{0}; };
当我创建 Bar
的实例时,似乎 a
和 b
都被初始化为零。这有保证吗?我在哪里可以找到规范中的内容?
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 member 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). If a member of a reference type is one of these remaining members, the program is ill-formed.
Foo
没有默认成员初始值设定项 (int b{0};
),因此 b
将通过空列表的列表初始化进行初始化,这意味着非 class 类型:b = int() // = 0
.