简体   繁体   English

默认的默认构造函数,为什么它不是用户提供的默认构造函数?

[英]A defaulted default constructor, why is it not a user-provided default constructor?

For example, clang does not compile this code, because, the defaulted default constructor for struct A below, A() = default; 例如, clang不编译此代码,因为,下面的struct A的默认默认构造struct AA() = default; is not considered to be user-provided. 不被视为用户提供。

struct A{ A() = default; };
const A a;

But if you look at [dcl.fct.def.general]/1 you'll see: 但如果你看[dcl.fct.def.general] / 1,你会看到:

function-body: 函数体:
ctor-initializer opt compound-statement ctor-initializer opt 复合语句
function-try-block 功能试块
= default ;
= delete ;

That is, = default; 也就是说, = default; is the function body for the default constructor A::A() , which is the same as saying that the definition A() = default; 是默认构造函数A::A()函数体 ,它与定义A() = default; above is equivalent to A(){} as {} is the body for a default constructor. 上面等价于A(){}因为{}是默认构造函数的主体。

By the way, g++ compiles the snippet above, but I know g++ has other issues in this regard, according to this comment by Jonathan Wakely. 顺便说一句, g++编译上面的代码片段,但我知道g++在这方面有其他问题,根据Jonathan Wakely的评论

Because the standard says so ( [dcl.fct.def.default]/5 ): 因为标准是这样说的( [dcl.fct.def.default] / 5 ):

A function is user-provided if it is user-declared and not explicitly defaulted or deleted on its first declaration. 如果函数是用户声明的,并且在第一个声明中未明确默认或删除,则用户提供该函数。

Doing it this way allows you to maintain the triviality property with = default; 这样做可以让你用= default;维护triviality属性= default; . Otherwise, there's no way to give a class with another constructor a trivial default constructor. 否则,没有办法给另一个构造函数的类一个普通的默认构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么用户提供的默认构造函数会导致未初始化的成员? - Why does a user-provided default constructor lead to an uninitialized member? 为什么 C++ 需要用户提供的默认构造函数来默认构造一个 const 对象? - Why does C++ require a user-provided default constructor to default-construct a const object? 用户提供的构造函数与显式默认的构造函数 - User-provided constructor vs explicitly defaulted one “没有用户提供的默认构造函数”警告仅与 gcc - “no user-provided default constructor” warning only with gcc 模板化默认构造函数 - Templated Defaulted default constructor 为什么我们需要一个const对象的用户提供的构造函数? - Why do we need a user-provided constructor for a const object? 显式默认默认构造函数和聚合 - Explicit defaulted default constructor and aggregates 为什么我可以使用默认的 &lt;=&gt; 而不是用户提供的调用 ==? - Why can I invoke == with a defaulted <=> but not a user-provided one? 为什么为联合或类似联合的 class 删除默认的默认构造函数? - Why is the defaulted default constructor deleted for a union or union-like class? 为什么显式默认析构函数会禁用默认移动构造函数? - Why does an explicitly defaulted destructor disable default move constructor?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM