In C++11 having in-class member initializers makes the struct/class not an aggregate — this was changed in C++14, however. This is something I found surprising when I first ran into it, the rationale for this restriction is that in-class initializers are pretty similar to a user defined constructor but the counter argument is that no one really expects that adding in-class initializers should make their class/struct a non-aggregate, I sure did not.
From the draft C++11 standard section 8.5.1
Aggregates (emphasis mine going forward):
An aggregate is an array or a class (Clause 9) with no user-provided
constructors (12.1), no brace-or-equal initializers for non-static
data members (9.2), no private or protected non-static data members
(Clause 11), no base classes (Clause 10), and no virtual functions
(10.3).
and in C++14 the same paragraph reads:
An aggregate is an array or a class (Clause 9) with no user-provided
constructors (12.1), no private or protected non-static data members
(Clause 11), no base classes (Clause 10), and no virtual functions
(10.3).
This change is covered in N3605: Member initializers and aggregates which has the following abstract:
Bjarne Stroustrup and Richard Smith raised an issue about aggregate
initialization and member-initializers not working together. This
paper proposes to fix the issue by adopting Smith's proposed wording
that removes a restriction that aggregates can't have
member-initializers.
This comment basically sums up the reluctance to allowing them to be aggregates:
Aggregates cannot have user-defined constructors and
member-initializers are essentially some kind of user-defined
constructor (element) (see also Core Defect 886). I'm not against this
extension, but it also has implications on what our model of
aggregates actually is. After acceptance of this extension I would
like to know how to teach what an aggregate is.
The revised version N3653 was adopted in May 2013.
Update
emsr points out that G++ 5.0 now supports C++14 aggregates with non-static data member initializers using either std=c++1y
or -std=c++14
:
struct A { int i, j = i; };
A a = { 42 }; // a.j is also 42
See it working live.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…