2015-04-01 54 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