如何在 C++ 类的初始化列表中初始化成员结构?

2021-12-23 00:00:00 list constructor initializer struct c++

我在 C++ 中有以下类定义:

I have the following class definitions in c++:

struct Foo {
  int x;
  char array[24];
  short* y;
};

class Bar {
  Bar();

  int x;
  Foo foo;
};

并希望在 Bar 类的初始化程序中将foo"结构(及其所有成员)初始化为零.可以这样做吗:

and would like to initialize the "foo" struct (with all its members) to zero in the initializer of the Bar class. Can this be done this way:

Bar::Bar()
  : foo(),
    x(8) {
}

...?

或者 foo(x) 在初始化列表中到底做了什么?

Or what exactly does the foo(x) do in the initializer list?

或者结构体是否甚至从编译器自动初始化为零?

Or is the struct even initialized automatically to zero from the compiler?

推荐答案

首先,你应该(必须!)阅读这个 c++ 常见问题.在您的情况下, Foo 确实是一个 POD 类,而 foo() 是一个 值初始化 :

First of all, you should (must !) read this c++ faq regarding POD and aggregates. In your case, Foo is indeed a POD class and foo() is a value initialization :

值初始化一个类型的对象T 表示:

To value-initialize an object of type T means:

  • 如果 T 是具有用户声明的构造函数 (12.1) 的类类型(第 9 条),则为默认构造函数
    for T 被调用(如果 T 没有可访问的默认构造函数,则初始化是错误的);
  • 如果 T 是一个没有用户声明的构造函数的非联合类类型,那么 T 的每个非静态数据成员和基类组件都是值初始化的;
  • 如果 T 是数组类型,则每个元素都进行值初始化;
  • 否则,对象被零初始化

所以是的,foo 将被零初始化.请注意,如果您从 Bar 构造函数中删除此初始化,则 foo 将只会是 default-initialized :

So yes, foo will be zero-initialized. Note that if you removed this initialization from Bar constructor, foo would only be default-initialized :

如果没有指定初始化器对象,并且对象是(可能是cv 限定的)非 POD 类类型(或其数组),对象应为默认初始化;如果对象是const 限定类型,基础类类型应具有用户声明的默认构造函数.否则,如果没有初始化器为非静态对象指定,对象及其子对象,如果有的话,有一个不确定的初始价值;

If no initializer is specified for an object, and the object is of (possibly cv-qualified) non-POD class type (or array thereof), the object shall be default-initialized; if the object is of const-qualified type, the underlying class type shall have a user-declared default constructor. Otherwise, if no initializer is specified for a nonstatic object, the object and its subobjects, if any, have an indeterminate initial value;

相关文章