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) 最近为什么const对象需要用户提供的默认构造函数?被标记为重复为什么C++需要用户提供的默认构造函数来默认构造一个const对象?.我正在使用coliru和rextexter来测试各种版本的gcc(g ++ - 4.7,g ++ - 4.8,g ++ - 4.9)和clang(3.4和3.5)以查看是否在较新版本的编译器中引入了这种行为.这里我们分别从两个问题中提取了两个测试用例:
class A {
public:
void f() {}
};
int main()
{
A a; // OK
const A b; // ERROR
a.f();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
和:
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 …Run Code Online (Sandbox Code Playgroud)