gpt4 book ai didi

c++ - 当初始化列表中没有更多元素时,是否初始化数组的其余元素

转载 作者:行者123 更新时间:2023-11-30 01:21:57 24 4
gpt4 key购买 nike

下面的行为是否定义明确?

#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
int a[10] = {1, 2, 3, 4, 5};
for(const auto &i: a)
cout << i << endl;
return 0;
}

输出:

1
2
3
4
5
0
0
0
0
0

最佳答案

是的,多余的元素被初始化为“零”(整数为 0, float 为 0.0,指向 NULL 的指针)。

更准确地说,C 标准要求它们被初始化,就好像它们具有static 存储持续时间一样:

C99 标准第 6.7.8.21 段:

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

6.7.8.10:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:

— if it has pointer type, it is initialized to a null pointer;

— if it has arithmetic type, it is initialized to (positive or unsigned) zero;

— if it is an aggregate, every member is initialized (recursively) according to these rules;

— if it is a union, the first named member is initialized (recursively) according to these rules.

该死的,这是 C++。 (除了@yuan 没有人意识到这一点,谢谢!)

所以 C++11 中的第 8.5.1.7 段:

To value-initialize an object of type T means:

— if T is a (possibly cv-qualified) class type (Clause 9) with a user-provided 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 (possibly cv-qualified) non-union class type without a user-provided constructor, then the object is zero-initialized and, if T’s implicitly-declared default constructor is non-trivial, that constructor is called.

— if T is an array type, then each element is value-initialized;

— otherwise, the object is zero-initialized.

8.5.1.5:

To zero-initialize an object or reference of type T means:

— if T is a scalar type (3.9), the object is set to the value 0 (zero), taken as an integral constant expression, converted to T; 103

— if T is a (possibly cv-qualified) non-union class type, each non-static data member and each base-class subobject is zero-initialized and padding is initialized to zero bits;

— if T is a (possibly cv-qualified) union type, the object’s first non-static named data member is zeroinitialized and padding is initialized to zero bits;

— if T is an array type, each element is zero-initialized;

— if T is a reference type, no initialization is performed.

关于c++ - 当初始化列表中没有更多元素时,是否初始化数组的其余元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17257828/

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