C++标准(第8.5节)说:
如果程序要求对const限定类型T的对象进行默认初始化,则T应为具有用户提供的默认构造函数的类类型.
为什么?在这种情况下,我无法想到为什么需要用户提供的构造函数.
struct B{
B():x(42){}
int doSomeStuff() const{return x;}
int x;
};
struct A{
A(){}//other than "because the standard says so", why is this line required?
B b;//not required for this example, just to illustrate
//how this situation isn't totally useless
};
int main(){
const A a;
}
Run Code Online (Sandbox Code Playgroud) 我有代码:
class A {
public:
A() = default;
private:
int i = 1;
};
int main() {
const A a;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它在g ++上编译很好(参见ideone),但在clang ++上失败并出现错误:
const类型'const A'的对象的默认初始化需要用户提供的默认构造函数
我在LLVM错误跟踪器上报告了这个问题,并使其无效.
我认为试图说服铿锵的开发者绝对毫无意义.另一方面,我没有看到这种限制的原因.
任何人都可以建议,如果C++ 11标准以某种方式暗示此代码无效?或者我应该向g ++报告错误?或许在语言规则方面有足够的自由来以多种方式处理这些代码?