简体   繁体   English

使用 {0} 初始化结构

[英]initializing struct with {0}

I'm debugging some code that essentially is identical to this:我正在调试一些基本上与此相同的代码:

struct Foo { int a; int b; };
struct Bar { Bar() {} Foo foo{0}; };

When I make an instance of Bar , it seems like both a and b are initialized to zero.当我创建Bar的实例时,似乎ab都被初始化为零。 Is this guaranteed?这是有保证的吗? Where can I find that in the spec?我在哪里可以在规范中找到它?

According to cppreference.com根据cppreference.com

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).如果初始值设定项子句的数量少于成员 [和基 (C++17 起)] 的数量或初始值设定项列表完全为空,则剩余成员 [和基 (C++17 起)] 将 [由它们的默认成员初始化器,如果在 class 定义中提供,否则 (C++14 起)] 按照通常的列表初始化规则(对非类类型和非聚合类执行值初始化)为空列表使用默认构造函数和聚合的聚合初始化)。 If a member of a reference type is one of these remaining members, the program is ill-formed.如果引用类型的成员是这些剩余成员之一,则程序格式错误。

Foo has no default member initializers ( int b{0}; ), so b will be initialized by list-initialization with an empty list, which means value-initialization for non-class types: b = int() // = 0 . Foo没有默认的成员初始化器 ( int b{0}; ),因此b将通过列表初始化以空列表进行初始化,这意味着非类类型的值初始化: b = int() // = 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM