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

标签 c++ standards-compliance c++98 compiler-bug

注意:我们在这里谈论的是(据说)符合 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/

相关文章:

c++ - C++ 中整数循环和迭代器循环之间的差异

没有序列点的 C++11?

c++ - 从作用于 map 的算法调用的仿函数可以接受 pair<K, V> 而不是 value_type 吗?

c++ - 构造函数的首选参数传递

xslt - XPATH 一致性

C++ new int[0]——它会分配内存吗?

c++ - 从字符串中修剪/删除无用的空格和制表符

c++ - 从默认参数推断模板参数

c++ - 模板案例的编译器警告,模板特化应涵盖

c++ - 如何使用 cmake 一次运行所有 gtest 文件?