默认构造函数不应将任何数据成员清零。但在某些情况下,似乎并非如此。
代码示例很简短。
#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/