简体   繁体   English

默认情况下是默认构造函数/赋值noexcept / constexpr吗?

[英]Is a defaulted constructor/assignment noexcept/constexpr by default?

So, my question is simple: 所以,我的问题很简单:

Is there any point in specifying a defaulted class constructor as noexcept or constexpr (or any other thing you could thing of)? 将默认类构造函数指定为noexceptconstexpr (或任何其他可能的东西)是否有任何意义?

struct foo
{
   foo() = default;
   // vs
   constexpr foo() noexcept = default;

   // same thing would apply for copy/move ctors and assignment operators
};

Would the two behave the same way? 两者的行为方式是否相同?

Does it depend on whether the class is POD? 这取决于课程是否为POD? For example with the above example both would behave the same way, while if for example I had a private member std::vector<int> v = { 1, 2, 3, 4 }; 例如,使用上面的示例,两者的行为方式相同,而如果我有一个私有成员std::vector<int> v = { 1, 2, 3, 4 }; which uses in-class assignment, foo() = default; 它使用类内赋值, foo() = default; would by default not be noexcept and not constexpr . 默认情况下不是noexcept而不是constexpr

By writing foo() = default; 通过编写foo() = default; does the compiler just pick the best version: noexcept if possible and constexpr if possible, etc? 编译器是否选择了最好的版本:如果可能的话, noexcept和尽可能的constexpr等等?

[dcl.fct.def.default]/2-3 : [dcl.fct.def.default] / 2-3

2 An explicitly-defaulted function that is not defined as deleted may be declared constexpr only if it would have been implicitly declared as constexpr . 2未被定义为删除的明确,违约函数可以声明constexpr只有它会被隐含声明为constexpr If a function is explicitly defaulted on its first declaration, 如果函数在其第一个声明中明确默认,

  • it is implicitly considered to be constexpr if the implicit declaration would be, and, 如果隐式声明是,则隐含地认为是constexpr ,并且,
  • it has the same exception specification as if it had been implicitly declared ([except.spec]). 它具有相同的异常规范,就好像它已被隐式声明([except.spec])。

3 If a function that is explicitly defaulted is declared with an exception-specification that is not compatible ([except.spec]) with the exception specification of the implicit declaration, then 3如果使用异常规范 ([except.spec])使用隐式声明的异常规范声明显式默认的函数,则

  • if the function is explicitly defaulted on its first declaration, it is defined as deleted; 如果函数在其第一个声明中明确默认,则将其定义为已删除;

  • otherwise, the program is ill-formed. 否则,该计划是不正确的。

In other words, foo() = default; 换句话说, foo() = default; , which is necessarily the first declaration of foo 's default constructor, will be " constexpr if possible" and " noexcept if possible". ,这必然是foo默认构造函数的第一个声明,如果可能的话,将是“ constexpr ”,如果可能的话,将是“ noexcept ”。 Explicitly writing constexpr and noexcept is still useful; 明确写constexprnoexcept仍然有用; it means "yell at me if it can't be constexpr / noexcept ". 它意味着“如果它不能是constexpr / noexcept就会对我大喊大叫”。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM