c++ - 什么会导致类中的数据成员初始化为零?

标签 c++ c++11 initialization

默认构造函数不应将任何数据成员清零。但在某些情况下,似乎并非如此。

代码示例很简短。

#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;
}

作为异常(exception),以上程序输出:

true

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

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

输出将是:

0
false

同理,如果给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

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

最佳答案

作为default initialization在这种情况下:

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

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

关于c++ - 什么会导致类中的数据成员初始化为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58620210/

相关文章:

c++ - Boost 1.57.0 程序选项 MSVS 2013 链接器错误

c++ - 正确使用 std::tuple?

c++ - C++ 中的默认初始化

c++ - 函数指针、Functor 还是 Lambda?

c++ - 是否有必要在互斥锁上调用 pthread_mutex_destroy?

c++ - 调用 Isolate::New() 后执行位置 0x0000000000000000 时发生访问冲突

c++ - 启动线程导致 abort()

java - 循环中 ArrayList 的错误初始化

Python:在同一实例上多次调用 __init__()

c++ - 如何在 Windows 上使用 MinGW 安装/启用 OpenMP for Eclipse?