简体   繁体   English

C++ 为什么成员没有默认初始化?

[英]C++ Why the members are not default initialized?

If I have a struct Foo and a struct Bar:如果我有一个 struct Foo 和一个 struct Bar:

struct Foo {
  int a, b;
};

struct Bar {
  Foo foo;  
  int c;
};

If I initialize a Bar and print the values I correctly get:如果我初始化一个Bar并打印我正确得到的值:

int main() {
  Bar bar = {}; // I call the default constructor
  std::cout << bar.foo.a << " "; // 0
  std::cout << bar.foo.b << " "; // 0
  std::cout << bar.c << std::endl; // 0

  return 0;
}

But now if I declare a constructor like this:但是现在如果我声明一个这样的构造函数:

struct Bar {
  Bar() : c(5) {}

  Foo foo;  
  int c;
};

I lose the default construction of Bar::foo and the program outputs 32764 0 5 !我失去了Bar::foo的默认构造,程序输出32764 0 5

Why am I forced to dumbly initialize every member variable like this:为什么我不得不像这样愚蠢地初始化每个成员变量:

struct Bar {
  Bar() : c(5) {}

  Foo foo{};  
  int c;
};

as long as I declare a constructor?只要我声明一个构造函数? Why doesn't the default construction works in this case?为什么在这种情况下默认构造不起作用?

In C++, if you have a default constructor, and the variables aren't initialized with the initializer list, then it default constructs to an indeterminate value.在 C++ 中,如果您有一个默认构造函数,并且变量没有使用初始化列表进行初始化,那么它默认构造为一个不确定的值。 This is a noted behaviour which hasn't been fixed, so I assume it's either intended, or more likely accepted.这是一个尚未修复的值得注意的行为,所以我认为它要么是有意的,要么更有可能被接受。

From CPP Reference :来自CPP 参考

Notes笔记

Default initialization of non-class variables with automatic and dynamic storage duration produces objects with indeterminate values (static and thread-local objects get zero initialized)具有自动和动态存储持续时间的非类变量的默认初始化产生具有不确定值的对象(静态和线程局部对象初始化为零)

References and const scalar objects cannot be default-initialized.引用和 const 标量对象不能默认初始化。

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

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