Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

c++ - Default Initialization Versus Zero Initialization

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?

My question is: Can someone explain this behavior? And ideally tell me what should be happening.

I have two classes:

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;
}

On gcc and Visual Studio I get:

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 gives me:

0
0

And Visual Studio gives me:

50790236
51005888

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

  • 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;

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...