c++ - 关于类类型静态数组的空初始化

标签 c++ arrays static initialization

当我运行静态代码分析器 QACPP 时,我收到了警告。根据 QACPP 文档,使用 {0} 进行初始化仅适用于内置类型。要初始化 A 类型的对象数组,必须使用 {}。如下:

int i[5] = {0};  // Only works with built-in types.
A   a[5] = {};   // OK, works with both built-in and class types

这是标准的 C++ 规则吗?据此,指向类类型的指针数组也必须用 {} 初始化,对吧?

这个语句是否:

A* ap[5] = {}

NULL 初始化 5 个指针?

当我使用 A* ap[5] = {NULL} 时,QACPP 向我发出警告,尽管代码即使在其他情况下也能完美编译和运行。


附加

我认为警告更多是因为数组是静态的。

这是我在文档中找到的解释:

There are many problems with the use of objects with static storage duration, particularly those declared outside of functions. If many functions can access a static object this situation may become difficult to maintain. Also, in the case of multi-threaded applications it becomes necessary to protect with mutex each static object that can be accessed concurrently. It is therefore a good idea to limit the scope of a static object as much as possible, so that you know where such object is accessed.

Namespace or class objects with static storage duration will be initialised at the start of the program, before calling main(), and the order of initialisation is unspecified. Reliance on the order of initialisation may lead to objects being used before they are initialised. If an exception is thrown as a result of initialising a non-local object the program will immediately terminate.

Block scope objects with static storage duration will be initialised when the function is first called. Therefore, it is best to use the singleton pattern instead of namespace objects and static data members. This entails wrapping the object in a function as a local static object, and having the function return a reference to this object.

最佳答案

是的,这是一个标准规则。数组是一个集合。聚合标准中明确提到了初始化规则。

Does this statement: A* ap[5] = {} intialise the 5 pointers with NULL?

QACPP throws me a warning when I used A* ap[5] = {NULL}

什么警告?也许警告是您只初始化了第一个元素,其他元素将保持为 NULL。当然,这可能是您需要的。但是,编译器只是警告你 :)

我觉得这个问答会很有趣。 What are Aggregates and PODs and how/why are they special?

关于c++ - 关于类类型静态数组的空初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6545012/

相关文章:

c++ - (为什么)我们可以在初始化时将非静态类成员分配给静态变量吗?

c++ - 在指针成员之前调用非指针成员的析构函数

c++ - 使用 GCC-4.8.1 在 MinGW 上编译 wxWidgets-2.8.12 时出错

java - 为什么 Oracle Java 提供的答案在寻址枚举集时使用私有(private)静态修饰符?

MySql - 使用同一表的某些字段的值更新表的某些字段

c - 为什么在 C 中逐列复制二维数组比逐行复制花费的时间更长?

function - C++ : using class member and static function of same name but different parameters fails

c++ - 在 omnet 中作为消息发送功能

c++ - Qt QML 单例智能感知

java - 为什么Java中函数修改数组[0]而不修改字符串?