为什么在下面的非 POD 类中 x 被初始化为零?
class test {
public:
void print() {
cout << x << endl;
}
private:
int x;
};
int main(int argc, char** argv)
{
test * tst = new test();
tst->print();
cout << is_pod<test>::value << endl;
}
tst->print() 和 is_pod() 都返回 0
最佳答案
这是 value-initialization 的结果没有用户提供的构造函数的类。
在本例中,T<b>()</b>
和new T<b>()</b>
首先执行零初始化:
if
T
is a class type with a default constructor that is neither user-provided nor deleted (that is, it may be a class with an implicitly-defined or defaulted default constructor), the object is zero-initialized and then it is default-initialized if it has a non-trivial default constructor;
zero-initialization的影响是:
if
T
is an non-union class type, all base classes and non-static data members are zero-initialized, and all padding is initialized to zero bits. The constructors, if any, are ignored.
和
if
T
is a scalar type, the object's initial value is the integral constant zero explicitly converted toT
.
关于c++ - 非POD的零初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59786415/