c – 默认构造一个整数数组是否会初始化它?

前端之家收集整理的这篇文章主要介绍了c – 默认构造一个整数数组是否会初始化它?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果我有一个带有数组成员的结构,并且我在结构的构造函数中显式调用了数组的默认构造函数,那么元素是否会默认构造? (在整数数组的情况下,这将意味着零初始化).
struct S
{
    S() : array() {}

    int array[SIZE];
};

...

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

使用gcc进行的快速测试表明情况确实如此,但我想确认我可以依赖这种行为.

(我注意到如果我没有在结构构造函数中显式默认构造数组,则数组元素具有随机值.)

解决方法

是的(突出我的):

(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://www.f2er.com/c/119799.html

猜你在找的C&C++相关文章