0

Consider following program:

#include <iostream>
struct Test
{
    int a;
};
int main()
{
    Test t=Test();
    std::cout<<t.a<<'\n';
}

Test t=Test(); value initializes a temporary & copy initializes it. (most compilers optimize out the copy operation (Source: value initialization)). But value initialization is introduced by C++03. What happens in C++98 when Test t=Test(); is executed? Is it guaranteed that I will get 0 as an output (value of t.a in this case) on any C++98 compiler? . Is it default initialization being performed in C++98?

Destructor
  • 14,123
  • 11
  • 61
  • 126
  • 2
    [This question](http://stackoverflow.com/questions/27349679/is-value-initialization-part-of-the-c98-standard-if-not-why-was-it-added-in) might be of interest to you. – TartanLlama Jan 18 '16 at 14:44

1 Answers1

3

C++ standard (1998)

[dcl.fct.def]

7 An object whose initializer is an empty set of parentheses, i.e., (), shall be default-initialized.

[dcl.init]

5 To zero-initialize storage for an object of type T means:

— if T is a scalar type (3.9), the storage is set to the value of 0 (zero) converted to T;

— if T is a non-union class type, the storage for each nonstatic data member and each base-class subobject is zero-initialized;

— if T is a union type, the storage for its first data member 89) is zero-initialized;

— if T is an array type, the storage for each element is zero-initialized;

— if T is a reference type, no initialization is performed.

To default-initialize an object of type T means:

— if T is a non-POD class type (clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

— if T is an array type, each element is default-initialized;

otherwise, the storage for the object is zero-initialized.

It appears that the temporary is default initialized, which means zero initialization for a POD type (which Test is) and therefore t.a == 0 is guaranteed.

Since C++03 this is value initialization and same guarantee remains.

It appears that the addition of value initialization and re-definition of default initialization in C++03, was to allow not zero-initializing scalars and POD types (in some contexts).

Community
  • 1
  • 1
eerorika
  • 232,697
  • 12
  • 197
  • 326