Default initialization of C++ Member arrays?
This is a simple question, but I can't seem to find a definitive answer.
If we have the following class:
class Test
{
...
char testArray[10];
...
};
When we create an instance of Test, what is the default value of testArray[1]?
If it was a local array, it would be uninitialized.
If it was a sta开发者_Go百科tic array, it would be initialized to 0.What does it do when the array is a class member?
From the standard, section 8.5 [dcl.init]
:
To default-initialize an object of type
T
means:
if
T
is a (possibly cv-qualified) class type (Clause 9), the default constructor forT
is called (and the initialization is ill-formed ifT
has no accessible default constructor);if
T
is an array type, each element is default-initialized;otherwise, no initialization is performed.
also section 12.6.2 [class.base.init]
:
In a non-delegating constructor, if a given non-static data member or base class is not designated by a mem-initializer-id (including the case where there is no mem-initializer-list because the constructor has no ctor-initializer) and the entity is not a virtual base class of an abstract class (10.4), then
- if the entity is a non-static data member that has a brace-or-equal-initializer, the entity is initialized as specified in 8.5;
- otherwise, if the entity is a variant member (9.5), no initialization is performed;
- otherwise, the entity is default-initialized (8.5).
So because the element type is char
, when each element is default-initialized, no initialization is performed. The contents are left with arbitrary values.
Unless, of course, it's a member of an instance of the class, and the instance has static storage duration. Then the whole instance is zero-initialized, array members and all, before execution begins.
It depends on may factors that you forgot to mention.
If your Test
has no user-defined constructor or your user-defined constructor makes no efforts to initialize the array, and you declare the object of type Test
as
Test test; // no initializer supplied
then it will behave in exactly the same way as you described above. For an automatic (local) object the contents of the array will remain unpredictable. For a static object the contents is guaranteed to be zero.
If your class has a user-defined constructor, then it will all depend on what constructor does. Again, keep in mind that static objects are always zero-initialized before any constructor has a chance to do anything.
If your class is an aggregate, then the content might depend on the aggregate initializer you supplied in the object declaration. For example
Test test = {};
will zero-initialize the array even for an automatic (local) object.
I believe that if you don't initialize it when you declare it, it can be set to anything. Sometimes it is an address or random looking value.
Best practice is to initialize after declaring.
精彩评论