初始化列表中的零初始化数组成员 [英] Zero-Initialize array member in initialization list

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

问题描述

我有一个带有数组成员的类,我想将其初始化为全零。

I have a class with an array member that I would like to initialize to all zeros.

class X
{
private:
    int m_array[10];
};

对于局部变量,有一种直接初始化为零的简单方法(请参见此处):

For a local variable, there is a straightforward way to zero-initialize (see here):

int myArray[10] = {};

此外,类成员 m_array 显然需要进行初始化,因为默认初始化int只会留下随机垃圾,如此处所述a>。

Also, the class member m_array clearly needs to be initialized, as default-initializing ints will just leave random garbage, as explained here.

但是,我可以看到两种针对成员数组的方法:

However, I can see two ways of doing this for a member array:

带有括号:

public:
    X()
    : m_array()
    {}

带花括号:

public:
    X()
    : m_array{}
    {}

都正确吗?两者在C ++ 11中有什么区别吗?

Are both correct? Is there any difference between the two in C++11?

推荐答案

使用()初始化任何成员执行值初始化。

使用默认构造函数和 {} 初始化任何类类型

Initialising any class type with a default constructor with {} performs value initialisation.

使用 {} 初始化任何其他聚合类型(包括数组)将执行列表初始化,并且等效于使用 {} {code>初始化集合的每个成员。

Initialising any other aggregate type (including arrays) with {} performs list initialisation, and is equivalent to initialising each of the aggregate's members with {}.

使用 {} 构造一个临时对象,该对象从 {} 初始化,并将引用绑定到该临时对象。

Initialising any reference type with {} constructs a temporary object, which is initialised from {}, and binds the reference to that temporary.

使用 {} 初始化任何其他类型将执行值初始化。

Initialising any other type with {} performs value initialisation.

因此,对于几乎所有类型,从 {} 初始化都会得到与值初始化相同的结果。您不能有引用数组,因此引用不能例外。您可能可以在没有默认构造函数的情况下构造聚合类类型的数组,但是编译器在确切规则上不一致。但是要回到您的问题,所有这些极端情况对您而言并不重要:对于您特定的数组元素类型,它们具有完全相同的效果。

Therefore, for pretty much all types, initialisation from {} will give the same result as value initialisation. You cannot have arrays of references, so those cannot be an exception. You might be able to construct arrays of aggregate class types without a default constructor, but compilers are not in agreement on the exact rules. But to get back to your question, all these corner cases do not really matter for you: for your specific array element type, they have the exact same effect.

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

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