默认初始化与零初始化 [英] Default Initialization Versus Zero Initialization

查看:184
本文介绍了默认初始化与零初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解gcc 4.8.1或Visual Studio 2015在默认初始化与值初始化方面的行为。

I cannot understand the behavior of gcc 4.8.1 or Visual Studio 2015 with respect to default initialization versus value initialization.

试图了解这些问题与可能遇到编译器错误之间的区别?

It doesn't help that I'm trying to understand the differences between these myself and possibly running into compiler bugs?

我的问题是:有人可以解释这种行为吗?最好告诉我应该怎么办。

我有两个课程:

class Foo{
    int _bar;
public:
    void printBar(){ cout << _bar << endl; }
};

class bar{
    int ent;
public:
    int getEnt(){return ent;}
};

我正在使用以下代码进行测试:

I'm using the following code to test:

int main()
{
    Foo foo;

    foo.printBar();
    Foo().printBar();

    bar b;

    cout << b.getEnt() << endl;

    return 0;
}

在gcc和Visual Studio上,我得到:

On gcc and Visual Studio I get:


134514795

0

0

134514795
0
0

现在,如果我将测试代码更改为:

Now if I change the test code to:

int main()
{
    Foo foo;

    foo.printBar();

    bar b;

    cout << b.getEnt() << endl;

    return 0;
}

gcc给我:


0

0

0
0

Visual Studio给了我:

And Visual Studio gives me:


50790236

51005888

50790236
51005888


推荐答案

像这样的没有用户定义的构造函数的类的默认初始化什么也不做,使每个琐碎的成员都具有不确定的值。

Default initialisation, of classes like this without user-defined constructors, does nothing, leaving each trivial member with an indeterminate value.

值初始化将零初始化每个成员。

Value initialisation will zero-initialise each member.

在第一种情况下,您正在打印:

In the first case, you're printing:


  • 默认初始化的 Foo foo的不确定值;

  • 值的零值-初始化 Foo()

  • 默认初始化的 bar b的不确定值;

  • the indeterminate value of a default-initialised Foo foo;
  • the zero value of a value-initialised Foo()
  • the indeterminate value of a default-initialised bar b;

第三个正好是零;也许是因为它重复使用了初始化后的临时值 Foo 的存储。

The third one happens to be zero; perhaps because it reuses the storage of the temporary value-initialised Foo.

在第二种情况下,打印两个默认初始化对象的不确定值。巧合的是,它们在一种情况下的值为零,而在另一种情况下则没有。

In the second case, you're printing the indeterminate values of two default-initialised objects. Coincidentally, they have zero values in one case but not the other.

这两个程序都具有未定义的行为,因为它们使用未初始化的值。

Both programs have undefined behaviour, since they use uninitialised values.

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

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