POD类型的零初始化

POD类型的零初始化

本文介绍了POD类型的零初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

struct Foo
{
    char name[10];
    int  i;
    double d;
};

我知道我可以使用以下方法对此类POD类型的所有成员进行零初始化:

I know that I can zero-initialize all the members of such POD type with:

Foo foo = {0};

我可以进一步简化为:

Foo foo = {};

像本机数组一样? (int arr[10] = {};)

Like native arrays? (int arr[10] = {};)

我不问何时使用{0}进行初始化,除了第一个成员以外的成员都将被零初始化.我知道这个问题的答案是肯定的.我问是否可以在语法上省略第一个0.

I'm not asking when initializing with {0}, will the members except the first are zero-initialized. I know the answer to that question is yes. I'm asking if the first 0 can be omitted syntactically.

我在该主题上找到的大多数教程都建议使用{0},而不使用{},例如,本指南,并解释为之所以有效,是因为聚合初始化规则是递归的; 比解释要复杂得多.

Most of the tutorials I found on this subject suggest using {0}, none using {}, e.g, this guide, and it's explained as This works because aggregate initialization rules are recursive;, which gives more confusion than explanation.

推荐答案

如所写,这是聚合初始化.适用的规则是(§8.5.1[dcl.init.aggr]/p7):

As written, this is aggregate initialization. The applicable rule is (§8.5.1 [dcl.init.aggr]/p7):

第8.5.4节[dcl.init.list]/p3的相关部分是:

The relevant parts of §8.5.4 [dcl.init.list]/p3 is:

  • 如果T是聚合,则执行聚合初始化(8.5.1).
  • 否则,如果初始化器列表中没有元素,并且T是具有默认构造函数的类类型,则对象为 值初始化.
  • [忽略不相关的项目]
  • 否则,如果初始化列表中没有元素,则该对象将被值初始化.
  • If T is an aggregate, aggregate initialization is performed (8.5.1).
  • Otherwise, if the initializer list has no elements and T is a class type with a default constructor, the object is value-initialized.
  • [irrelevant items omitted]
  • Otherwise, if the initializer list has no elements, the object is value-initialized.

简而言之,子聚合是从空的初始值设定项列表中递归地进行聚合初始化的.其他所有的东西都是价值初始化的.因此最终结果是所有东西都被值初始化,而所有东西都是POD,值初始化意味着零初始化.

In short, sub-aggregates are recursively aggregate-initialized from an empty initializer list. Everything else is value-initialized. So the end result is everything being value-initialized, with everything being a POD, value-initialization means zero-initialization.

如果T是POD而不是聚合,则聚合初始化不适用,因此您遇到了§8.5.4[dcl.init.list]/p3中的第二个要点,这将导致值初始化代替整个对象. POD类必须具有一个琐碎的(且不是用户提供的)默认构造函数,因此对它们的值初始化也意味着零初始化.

If T is POD but not an aggregate, then aggregate initialization doesn't apply, so you hit the second bullet point in §8.5.4 [dcl.init.list]/p3, which results in value-initialization of the entire object instead. POD classes must have a trivial (and so not-user-provided) default constructor, so value-initialization for them means zero-initialization as well.

这篇关于POD类型的零初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 11:57