Default Initialization Versus Zero Initialization

前端 未结 4 581
Happy的楠姐
Happy的楠姐 2020-12-20 05:14

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 tr

4条回答
  •  [愿得一人]
    2020-12-20 06:05

    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.

提交回复
热议问题