简体   繁体   中英

C++ Why the members are not default initialized?

If I have a struct Foo and a 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:

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 !

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. This is a noted behaviour which hasn't been fixed, so I assume it's either intended, or more likely accepted.

From CPP Reference :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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