Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will default-constructing an integer array zero-initialize it?

If I have a structure with an array member, and I explicitly call the default constructor of the array in the structure's constructor, will the elements get default-constructed? (In the case of an integer array, this would mean getting zero-initialized).

struct S
{
    S() : array() {}

    int array[SIZE];
};

...

S s;
// is s.array zero-initialized?

A quick test with gcc suggests that this is the case, but I wanted to confirm that I can rely on this behaviour.

(I have noticed that if I don't explicitly default-construct the array in the structure constructor, the array elements have random values.)

like image 537
HighCommander4 Avatar asked Jun 27 '11 21:06

HighCommander4


1 Answers

Yes (highlighting mine):

(C++03 8.5)

To value-initialize an object of type T means:

  • if T is a class type (clause 9) with a user-declared constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

  • if T is a non-union class type without a user-declared constructor, then every non-static > data member and baseclass component of T is value-initialized

  • if T is an array type, then each element is value-initialized;

  • otherwise, the object is zero-initialized

...

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

like image 151
Oliver Charlesworth Avatar answered Oct 05 '22 05:10

Oliver Charlesworth