C++标准(第8.5节)说:



为什么?我想不出在这种情况下为什么需要用户提供的构造函数的任何原因。

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;
}

最佳答案

这被认为是缺陷(针对该标准的所有版本),并由Core Working Group (CWG) Defect 253解决。 http://eel.is/c++draft/dcl.init#7中标准状态的新措词



该措辞实质上意味着显而易见的代码有效。如果初始化所有基数和成员,则可以说A const a;,而不管如何或是否拼写任何构造函数。

struct A {
};
A const a;

从4.6.4开始,gcc已经接受了这一点。 clang从3.9.0版开始接受此设置。 Visual Studio也接受这一点(至少在2017年,不确定是否更快)。

10-07 19:17
查看更多