问题描述
这个问题是针对C ++ 11的。
This question is for C++11.
在以下结构 A 中,将始终 x
In the following struct A, will x always be 42, when the default constructor is used?
struct A{
A() = default;
private:
int x = 42;
}
简而言之,我想知道默认构造函数是否保证默认成员值会被设置。
In short, I'm wondering if the default constructor guarantees that default member values will be set.
推荐答案
是。
不幸的是下面的措词来自今天的标准草案,但是原理在C ++ 11中是相同的。
Unfortunately the wording below is from the standard draft as of today, but the principle is the same in C++11.
在非委托构造函数中,如果给定的潜在构造子对象未由 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:
- 如果实体是具有默认成员初始值设定项(
[class.mem]
)和
- 的非静态数据成员构造函数的类是联合(
[class.union]
),并且该联合的其他任何变体成员都没有由 mem-initia指定lizer-id 或 - 构造函数的类不是联合体,并且,如果实体是匿名联合体的成员,则该联合体的其他成员都不会由 mem-initializer-id ,实体是根据
[dcl.init]
中指定的默认成员初始化程序进行初始化的;
- 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 - 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]
;
[..]
紧随上面引用的段落。
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.
这篇关于具有类成员默认值的C ++ 11默认构造函数行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!