以下代码非常简单,我希望它可以编译良好。
struct A
{
struct B
{
int i = 0;
};
B b;
A(const B& _b = B())
: b(_b)
{}
};
我已经使用g ++ 4.7.2、4.8.1,clang ++ 3.2和3.3测试了此代码。除了此代码的g ++ 4.7.2 segfaults(http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57770)之外,其他经过测试的编译器给出的错误消息也没有太多解释。
g ++ 4.8.1:
test.cpp: In constructor ‘constexpr A::B::B()’:
test.cpp:3:12: error: constructor required before non-static data member for ‘A::B::i’ has been parsed
struct B
^
test.cpp: At global scope:
test.cpp:11:23: note: synthesized method ‘constexpr A::B::B()’ first required here
A(const B& _b = B())
^
clang ++ 3.2和3.3:
test.cpp:11:21: error: defaulted default constructor of 'B' cannot be used by non-static data member initializer which appears before end of class definition
A(const B& _b = B())
^
使此代码可编译是可能的,并且似乎没有什么区别。有两种选择:
struct B
{
int i = 0;
B(){} // using B()=default; works only for clang++
};
要么
struct B
{
int i;
B() : i(0) {} // classic c++98 initialization
};
这段代码是真的不正确还是编译器错误?
internal compiler error: Segmentation fault
对此代码说...