开发者

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

开发者 https://www.devze.com 2023-03-15 15:10 出处:网络
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-constru开发者_StackOverflow中文版c

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-constru开发者_StackOverflow中文版cted? (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.)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消