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

混江龙づ霸主 提交于 2019-12-21 11:01:23

问题


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.)


回答1:


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.



来源:https://stackoverflow.com/questions/6499263/will-default-constructing-an-integer-array-zero-initialize-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!