且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

具有类成员默认值的C ++ 11默认构造函数行为

更新时间:2022-12-05 14:27:29

是。

不幸的是下面的措词来自今天的标准草案,但是原理在C ++ 11中是相同的。

Unfortunately the wording below is from the standard draft as of today, but the principle is the same in C++11.


[class.default.ctor] / 4 一个默认构造函数,默认为默认值,未定义为Delete,当它为 odr用过的 [basic.def.odr] )创建其类类型的对象( [intro.object] ),需要进行常量评估( [expr.const] ),或者在首次声明后明确将其默认为默认值。 隐式定义的默认构造函数执行该类的初始化集,该初始化集由该类的用户编写的默认构造函数执行,而没有 ctor-initializer [class.base.init] )和一个空的复合语句

[class.default.ctor]/4 A default constructor that is defaulted and not defined as deleted is implicitly defined when it is odr-used ([basic.def.odr]) to create an object of its class type ([intro.object]), when it is needed for constant evaluation ([expr.const]), or when it is explicitly defaulted after its first declaration. The implicitly-defined default constructor performs the set of initializations of the class that would be performed by a user-written default constructor for that class with no ctor-initializer ([class.base.init]) and an empty compound-statement.

[class.base.init] / 9 在非委托构造函数中,如果给定的潜在构造子对象未由 mem-initializer-id 指定(包括没有 mem-initializer的情况-list ,因为构造函数没有 ctor-initializer ),则:

[class.base.init]/9 In a non-delegating constructor, if a given potentially constructed subobject 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), then:


  1. 如果实体是具有默认成员初始值设定项( [class.mem] )和

  1. 的非静态数据成员构造函数的类是联合( [class.union] ),并且该联合的其他任何变体成员都没有由 mem-initia指定lizer-id

  2. 构造函数的类不是联合体,并且,如果实体是匿名联合体的成员,则该联合体的其他成员都不会由 mem-initializer-id 实体是根据 [dcl.init] 中指定的默认成员初始化程序进行初始化的;

  1. the constructor's class is a union ([class.union]), and no other variant member of that union is designated by a mem-initializer-id or
  2. the constructor's class is not a union, and, if the entity is a member of an anonymous union, no other member of that union is designated by a mem-initializer-id, the entity is initialized from its default member initializer as specified in [dcl.init];



[..]






简而言之,我想知道默认构造函数是否保证将设置默认成员值。

In short, I'm wondering if the default constructor guarantees that default member values will be set.

确切的示例紧随上面引用的段落。

An example of exactly this follows the passage latterly quoted above.

但是,如果要定义 A :: A()并为 x 它将优先于内联初始化程序

However, if you were to define A::A() and provide an initialiser for x, it would take precedence over the inline initialiser.