C ++成员数组的默认初始化? [英] Default initialization of C++ Member arrays?

查看:282
本文介绍了C ++成员数组的默认初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



如果我们有以下类:

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

...
};

当我们创建一个Test实例时,testArray [1]的默认值是什么? p>

如果是本地数组,它将是未初始化的。

如果它是一个静态数组,它将被初始化为0.



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

解决方案

标准,第8.5节 [dcl.init]


T 类型的对象表示:




  • if T 是(可能是cv限定的)类类型(第9条),调用 T 的默认构造函数-formed if T 没有可访问的默认构造函数);


  • if T 是数组类型,每个元素都是默认初始化 ;




还有12.6.2节 [class.base.init]


在非委托构造函数中,如果a给定非静态数据成员或基类不是由mem-initializer-id 指定的(包括没有 mem-initializer-list 的情况,因为构造函数没有 ctor-initializer ),实体不是抽象类的虚拟基类(10.4),




  • 如果实体是具有括号或初始值括号的非静态数据成员,则按8.5中所述初始化实体;

  • 否则,如果实体是变量成员(9.5),则不执行初始化;

  • 否则,实体被默认初始化(8.5) li>

因为元素类型是 char 当每个元素默认初始化时,不执行初始化。



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


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

这篇关于C ++成员数组的默认初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆