gpt4 book ai didi

c++ - C++成员数组的默认初始化?

转载 作者:IT老高 更新时间:2023-10-28 21:51:47 24 4
gpt4 key购买 nike

这是一个简单的问题,但我似乎找不到明确的答案。

如果我们有以下类:

class Test
{
...
char testArray[10];

...
};

当我们创建Test实例时,testArray[1]的默认值是多少?

如果是本地数组,则未初始化。
如果是静态数组,则初始化为0。

当数组是类成员时它会做什么?

最佳答案

来自标准,第 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.

还有第 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).

所以因为元素类型是char,所以当每个元素default-initialized时,不进行初始化。内容保留任意值。

当然,除非它是类实例的成员,并且该实例具有静态存储持续时间。然后整个实例零初始化,数组成员和所有,在执行开始之前。

关于c++ - C++成员数组的默认初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7760291/

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