c++ - 非POD的零初始化

标签 c++

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

相关文章:

c# - 需要帮助选择数据库服务器

c++ - 在 OpenCV 中使用轮廓?

c++ - 从 void* 到 DWORD 的指针截断

c++:从 vector::insert 返回迭代器

c++ - 哪个对数组清零最快?

c++ - 在不同的线程上发送和接收

c++ - 如何从输入文件(文本文件)中读取并将输入验证为有效整数?

c++ - 使用较旧版本的 MFC 和较新版本的 Visual Studio

c++ - 依赖子目录兄弟的介子目标

c++ - 模板的成员 typedef 在 VS 而非 GCC 中用于参数未声明的标识符