在C ++中默认初始化 [英] default initialization in C++

查看:135
本文介绍了在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.

这篇关于在C ++中默认初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆