是它允許標準類集合初始化:C++ 11與非靜態成員初始化
struct A
{
int a = 3;
int b = 3;
};
A a{0,1}; // ???
這是類仍然聚集? clang
接受此代碼,但gcc
不接受此代碼。
是它允許標準類集合初始化:C++ 11與非靜態成員初始化
struct A
{
int a = 3;
int b = 3;
};
A a{0,1}; // ???
這是類仍然聚集? clang
接受此代碼,但gcc
不接受此代碼。
但是,在具有類內成員初始值設定項的C++ 11中,結構/類不是聚合—,但在C++ 14中對此進行了更改。當我第一次碰到它的時候,我發現這是令人驚訝的,這個限制的基本原理是類內初始化與用戶定義的構造非常類似,但反說法是,沒有人真的希望添加類內初始化可以使他們的類/結構是非聚合的,我當然沒有。
從draft C++11 standard部分8.5.1
聚集(重點煤礦前進):
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).
和C++14同款曰:
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).
這種變化是覆蓋在N3605: Member initializers and aggregates其中有以下摘要:
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.
這基本上評論不願意總結,以使他們能夠成爲聚集:
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.
更新
EMSR指出G++ 5.0 now supports C++14 aggregates with non-static data member initializers使用或者std=c++1y
或-std=c++14
:
struct A { int i, j = i; };
A a = { 42 }; // a.j is also 42
看到它的工作live。
所以它似乎是不完整的問題gcc標準支持 – Bikineev 2014-11-25 03:56:40
@Bikineev嗯,你使用的是什麼版本的'gcc'?我無法使用'-std = C++ 11'使用從'4.7'到'4.9'的'gcc'重現。你能否澄清你的問題,你說'clang'接受它,我想你的意思是'gcc'? – 2014-11-25 03:59:25
我使用gcc 4.9.1。我的意思是gcc不支持這個建議。我得到:「錯誤:沒有匹配函數調用'A :: A(<大括號括號初始化列表>)'」 – Bikineev 2014-11-25 07:01:01