我不明白为什么我会这样做:
struct S {
int a;
S(int aa) : a(aa) {}
S() = default;
};
Run Code Online (Sandbox Code Playgroud)
为什么不说:
S() {} // instead of S() = default;
Run Code Online (Sandbox Code Playgroud)
为什么要为此引入一个新关键字?
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)