gpt4 book ai didi

c++数组零初始化: Is this a bug,或者这是正确的吗?

转载 作者:IT老高 更新时间:2023-10-28 22:41:38 27 4
gpt4 key购买 nike

注意:我们在这里谈论的是(据说)符合 C++98 的编译器。这不是 C++11 问题。

我们的一个编译器有一个奇怪的行为,我们不确定这是否正常或者这是一个编译器错误:

// This struct has a default constructor
struct AAA
{
AAA() : value(0) {}
int value ;
} ;

// This struct has a member of type AAA and an array of int, both surrounded
// by ints
struct BBB
{
int m_a ;
AAA m_b ;
int m_c ;
int m_d[42] ;
} ;

当 BBB 这样初始化时:

BBB bbb = {0} ;

我们期望 BBB 的所有 POD 成员(包括 m_d,int 数组)都被初始化为零,并且 BBB 的所有非 POD 成员都被构造。

这适用于 AIX 的 native 编译器、Linux/GCC-3.4、Windows/VisualC++...但不适用于 Solaris/SunStudio,其中只有非数组成员被零初始化。

我们在 C++98 标准(草稿文档)中做了一些研究,发现以下内容:

[12.6.1 - 2]

When an aggregate (whether class or array) contains members of class type and is initialized by a brace-enclosed initializer-list (8.5.1), each such member is copy-initialized (see 8.5) by the corresponding assignment-expression. If there are fewer initializers in the initializer-list than members of the aggregate, each member not explicitly initialized shall be default-initialized (8.5).

然后:

[8.5 - 5]

To zero-initialize storage for an object of type T means:
if T is a scalar type (3.9), the storage is set to the value of 0 (zero) converted to T ;
— if T is a non-union class type, the storage for each nonstatic data member and each base-class subobject is zero-initialized;
— if T is a union type, the storage for its first data member 89) is zero-initialized;
— if T is an array type, the storage for each element is zero-initialized;
— if T is a reference type, no initialization is performed.

然后:

To default-initialize an object of type T means:
— if T is a non-POD class type (clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
if T is an array type, each element is default-initialized;
otherwise, the storage for the object is zero-initialized.

我的阅读方式:SunStudio 应该零初始化整数数组 (BBB::m_d)

奇怪的事情:如果我们从 AAA 中删除默认构造函数,那么 BBB 中的所有内容都是零初始化的。

问题:当 SunStudio 未能对包含非 POD 的结构的整数数组进行零初始化时,它的行为是否标准?或者这是一个编译器错误?

最佳答案

这确实是 Sun/Solaris 的一个错误。你写的确实是应该发生的,你写的一切都是正确的。

关于c++数组零初始化: Is this a bug,或者这是正确的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18308941/

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