Default initialization of C++ Member arrays?

前端 未结 3 795
萌比男神i
萌比男神i 2020-12-15 18:21

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];

...         


        
3条回答
  •  温柔的废话
    2020-12-15 19:06

    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 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, 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.

提交回复
热议问题