2015-04-01 95 views
6

我嘗試使用值初始化與值初始化的構造函數的成員(我不知道如果我真的使用良好的條件......)統一和值初始化

所以......當我定義:

struct A 
{ 
    int a_; 
}; 

我能使用:

A a{5}; 
assert(m.a_==5); 

但是,如果我想使用底架初始化和初始化列表構造

struct B 
{ 
    int b_ {1}; 
}; 

這並不編譯(C++ 14:http://ideone.com/MQ1FMU):

B b{2}; 

以下是錯誤:

prog.cpp:19:7: error: no matching function for call to 'B::B(<brace-enclosed initializer list>)' 
    B b{2}; 
    ^
prog.cpp:19:7: note: candidates are: 
prog.cpp:10:8: note: constexpr B::B() 
struct B 
     ^
prog.cpp:10:8: note: candidate expects 0 arguments, 1 provided 
prog.cpp:10:8: note: constexpr B::B(const B&) 
prog.cpp:10:8: note: no known conversion for argument 1 from 'int' to 'const B&' 
prog.cpp:10:8: note: constexpr B::B(B&&) 
prog.cpp:10:8: note: no known conversion for argument 1 from 'int' to 'B&&' 

有什麼區別,概念明智? 非常感謝!

+0

嗯,我認爲這是因爲'B'不是一個聚合,但它實際上似乎滿足要求,據我所知。這簡直是​​不平凡的。 – 2015-04-01 20:30:17

+1

請注意,Ideone.com上的「C++ 14」是g ++ - 4.9.2,它不符合C++ 14標準(由此編譯錯誤證明!) – Casey 2015-04-01 22:10:57

回答

2

在C++ 11規則下,B不是聚合類型。 C++ 11 [dcl.init.aggr]/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).

B只有一個默認的構造,並且因此不能從支撐-初始化列表{2}初始化。

C++ 14允許支持或等於初始化程序用於聚合中的非靜態數據成員。 N4140 [dcl.init.aggr]/1:

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).

隨着相當直接的語義:字段其中沒有指定的初始化從它們支架 - 或等於初始值設定如果任何初始化,否則初始化{} [dcl.init.aggr]/7:

If there are fewer initializer-clauses in the list than there are members in the aggregate, then each member not explicitly initialized shall be initialized from its brace-or-equal-initializer or, if there is no brace-or-equal-initializer, from an empty initializer list (8.5.4).

你的程序是有效的因而C++ 14(DEMO)。本質上,在C++ 11中禁止使用括號或相等初始值設定項是C++ 14糾正的一個錯誤。

+0

非常感謝您的詳細解答!我想我應該用另一個C++ 14編譯器進行測試以確保... – fp12 2015-04-02 13:58:50