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

标签 c++ arrays initialization default-constructor

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

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/

相关文章:

c++ - 从文件中读取输入并存储到二维数组中

c++ - 这个模式在 C++ 中有效吗?

字符数组长度函数为 1、2、3、ENTER 返回 5,但在其他方面似乎没问题

java - 并行执行 Spring 初始化 Bean

c++ - Qt + CMake + VC++ 生成命令提示符

c++ - 编译器给出 lambda 函数转换错误

arrays - 使用 For 循环连接数组

jquery - 如何根据 jQuery 中对象数组的比较来更改键值?

c - 未初始化的变量如何获得随机值?

forms - Delphi:应用程序初始化 - 最佳实践/方法