其他分享
首页 > 其他分享> > c – 默认情况下是默认构造函数/赋值noexcept / constexpr吗?

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

作者:互联网

所以,我的问题很简单:

将默认类构造函数指定为noexcept或constexpr(或任何其他可能的东西)是否有任何意义?

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

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

两者的行为方式是否相同?

这取决于课程是否为POD?
例如,使用上面的示例,两者的行为方式相同,而如果我有一个私有成员std :: vector< int> v = {1,2,3,4};它使用类内赋值,foo()= default;默认情况下不是noexcept而不是constexpr.

通过编写foo()= default;编译器是否选择了最好的版本:如果可能的话,noexcept和尽可能的constexpr等等?

解决方法:

[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. If a function is explicitly defaulted on its first
declaration,

  • it is implicitly considered to be constexpr if the implicit declaration would be, and,
  • it has the same exception specification as if it had been implicitly declared ([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

  • if the function is explicitly defaulted on its first declaration, it is defined as deleted;

  • otherwise, the program is ill-formed.

换句话说,foo()= default;,它必然是foo默认构造函数的第一个声明,如果可能的话,将是“constexpr”,如果可能的话,将是“noexcept”.明确写constexpr和noexcept仍然有用;它意味着“如果它不能是constexpr / noexcept就会对我大喊大叫”.

标签:c,c11,c14
来源: https://codeday.me/bug/20191007/1868892.html