gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:28:37 24 4
gpt4 key购买 nike

当我运行静态代码分析器 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/

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