When I ran static code analyzer QACPP, I got a warning. According to the QACPP documentation, initializing with {0} only works for built in types. To initialize an array of objects of type A, {} must be used. As below:
int i[5] = {0}; // Only works with built-in types.
A a[5] = {}; // OK, works with both built-in and class types
Is this a standard C++ rule? According to this, an array of pointers to a class type must also be initialized with {}, right?
Does this statement:
A* ap[5] = {}
initialise the 5 pointers with NULL?
QACPP throws me a warning when I used A* ap[5] = {NULL}, though the code compiles and works perfectly even otherwise.
Additional
I think the warning was more because the array is static.
And here is the explanation I found in the documentation:
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.
Yes, it is a standard rule. An array is an aggregate. The rules of initialization are explicitly mentioned in the standard for aggregates.
Yes
What warning? Maybe the warning is that you initialized only the first element, and the others will stay NULL. Of course, it may be what you need. But then, the compiler is just warning you 🙂
I think this question and answer will be very interesting. What are Aggregates and PODs and how/why are they special?