默认情况下是否默认的构造函数/赋值为noexcept / constexpr? [英] Is a defaulted constructor/assignment noexcept/constexpr by default?
问题描述
所以,我的问题很简单:
So, my question is simple:
将默认的类构造函数指定为 noexcept
有什么意义吗?或 constexpr
(或您可能会想到的其他任何东西)?
Is there any point in specifying a defaulted class constructor as noexcept
or constexpr
(or any other thing you could thing of)?
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?
这是否取决于类是否为POD?
例如,在上面的示例中,两者的行为相同,而例如,如果我有一个私有成员 std :: vector< int> v = {1,2,3,4};
使用类内赋值, foo()=默认值;
默认不为 noexcept
而不是 constexpr
。
Does it depend on whether the class is 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 };
which uses in-class assignment, foo() = default;
would by default not be noexcept
and not constexpr
.
通过编写 foo()=默认值;
编译器是否会选择最佳版本: noexcept
(如果可能)和 constexpr
,如果可能,等等?
By writing foo() = default;
does the compiler just pick the best version: noexcept
if possible and constexpr
if possible, etc?
推荐答案
2未定义为删除的显式默认函数只有在隐式声明$ b $的情况下,才可以将
声明为constexpr
。 b为constexpr
。如果某个函数在其第一个
声明中显式默认为
2 An explicitly-defaulted function that is not defined as deleted may be declared
constexpr
only if it would have been implicitly declared asconstexpr
. If a function is explicitly defaulted on its first declaration,
- ,则该函数隐式视为
constexpr
如果隐式声明是,并且 - 它具有与隐式声明相同的异常规范([except.spec])。 li>
- 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如果使用
exception-specification 声明的默认值明确声明的函数不是与
兼容([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()=默认值;
,它必须是 foo
的默认构造函数的第一个声明,如果可能的话,将是 constexpr
和 无例外
。显式编写 constexpr
和 noexcept
仍然有用;它的意思是如果不能 constexpr
/ noexcept
大叫我。
In other words, foo() = default;
, which is necessarily the first declaration of foo
's default constructor, will be "constexpr
if possible" and "noexcept
if possible". Explicitly writing constexpr
and noexcept
is still useful; it means "yell at me if it can't be constexpr
/noexcept
".
这篇关于默认情况下是否默认的构造函数/赋值为noexcept / constexpr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!