gpt4 book ai didi

c++ - 默认构造一个整数数组会对其进行零初始化吗?

转载 作者:可可西里 更新时间:2023-11-01 18:25:55 26 4
gpt4 key购买 nike

如果我有一个包含数组成员的结构,并且我在结构的构造函数中显式调用了数组的默认构造函数,元素是否会被默认构造? (在整数数组的情况下,这意味着进行零初始化)。

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.

关于c++ - 默认构造一个整数数组会对其进行零初始化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6499263/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com