gpt4 book ai didi

c++ - 非POD的零初始化

转载 作者:行者123 更新时间:2023-12-02 02:49:32 26 4
gpt4 key购买 nike

为什么在下面的非 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 to T.

关于c++ - 非POD的零初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59786415/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com