在C ++中默认初始化

在C ++中默认初始化

问题描述:

我有一个关于C ++中的默认初始化的问题。我被告知非POD对象将被自动初始化。但我很困惑的代码下面。

I have a question about the default initialization in C++. I was told the non-POD object will be initialized automatically. But I am confused by the code below.

为什么当我使用指针时,变量i初始化为0,但是当我声明一个局部变量时,它不是。我使用g ++作为编译器。

Why when I use a pointer, the variable i is initialized to 0, however, when I declare a local variable, it's not. I am using g++ as the compiler.

class INT {
    public: int i;

};

int main () {

    INT* myint1 = new INT;
    INT myint2;
    cout<<"myint1.i is "<<myint1->i<<endl;
    cout<<"myint2.i is "<<myint2.i<<endl;

    return 0;
}

输出为

myint1.i is 0

myint1.i is 0

myint2.i is -1078649848

您需要在INT中声明一个c'tor,并强制'i'为一个明确定义的值。

You need to declare a c'tor in INT and force 'i' to a well-defined value.

class INT {
public:

    INT() : i(0) {}

 ...
};

i 仍然是POD因此不会默认初始化。它不会有什么区别,无论你是在堆栈还是堆上分配 - 在这两种情况下,如果 i 是未定义的值。

i is still a POD, and is thus not initialized by default. It doesn't make a difference whether you allocate on the stack or from the heap - in both cases, the value if i is undefined.