什么会导致 class 中的数据成员初始化为零?

What will cause the data members in class initialized to zeros?

默认构造函数不应将任何数据成员清零。但在某些情况下,似乎不是这样的。

代码示例很简短。

#include <iostream>

using namespace std;

class Foo {
public:
  int val;
  Foo() = default;
};

int main() {
  Foo bar;
  if (bar.val != 0) {
    cout << "true" << endl;
  } else {
    cout << "false" << endl;
  }
  return 0;
}

如有例外,以上程序输出:

true

但是,如果添加了 bar 数据成员的打印语句,var 成员将被初始化为零:

...
int main() {
  Foo bar;
  cout << bar.val << endl;
  ...
}

输出将是:

0
false

同理,如果给class添加虚函数和析构函数Foo

#include <iostream>

using namespace std;

class Foo {
public:
  virtual void Print() {}
  ~Foo() {}
  int val;
  Foo() = default;
};

int main() {
  Foo bar;
  if (bar.val != 0) {
    cout << "true" << endl;
  } else {
    cout << "false" << endl;
  }
  return 0;
}

或者只是初始化栏对象:

class Foo {
public:
  int val;
  Foo() = default;
};

int main() {
  Foo bar = Foo();
  ...
}

输出:

false

那么影响class的数据成员值的原因是什么?不应该所有这些测试输出 true?

在这种情况下为 default initialization

otherwise, nothing is done: the objects with automatic storage duration (and their subobjects) are initialized to indeterminate values.

请注意,不确定值包括 0,这也是一个有效结果。顺便说一句,读取这些不确定的值会导致 UB。