问题描述
两者之间有区别吗?
X() = default;
和
constexpr X() = default;
在常量表达式中默认构造类很好,所以这两个示例之间有区别吗?我应该在另一个上使用吗?
Default-constructing the class within constant expressions work fine, so is there a difference between these two examples? Should I use one over the other?
推荐答案
因为隐式构造函数实际上是 constexpr
在您的情况下…
Since the implicit constructor is actually constexpr
in your case…
[C ++ 11:7.1.5 / 3]:
constexpr
函数的定义应满足以下约束:
[C++11: 7.1.5/3]:
The definition of a constexpr
function shall satisfy the following constraints:
- it不得为虚拟(10.3);
- 其返回类型应为文字类型;
- 其每个参数类型均应为文字类型;
- 其功能主体应为
=删除
,=默认值
,或者仅包含
- null语句的 b $ b
- static_assert-declarations
-
typedef
声明和 alias-declarations ,它们未定义类或枚举, - 使用声明,
- using指令,
- 和一个返回语句;
- it shall not be virtual (10.3);
- its return type shall be a literal type;
- each of its parameter types shall be a literal type;
- its function-body shall be
= delete
,= default
, or a compound-statement that contains only- null statements,
- static_assert-declarations
typedef
declarations and alias-declarations that do not define classes or enumerations,- using-declarations,
- using-directives,
- and exactly one return statement;
…声明实际上是等效的:
… the declarations are actually equivalent:
- 该函数被隐式认为是
constexpr
如果隐式声明为, - 它被隐式认为具有相同的 exception-specification ,就好像它已被隐式声明(15.4),
- 对于复制构造函数,move构造函数,复制赋值运算符或move赋值运算符而言,它应具有
- it is implicitly considered to be
constexpr
if the implicit declaration would be, - it is implicitly considered to have the same exception-specification as if it had been implicitly declared (15.4), and
- in the case of a copy constructor, move constructor, copy assignment operator, or move assignment operator, it shall have the same parameter type as if it had been implicitly declared.
所以要么—
So do either — it doesn't matter.
在一般情况下,如果您确实希望构造函数为
constexpr
,最好保留关键字,这样如果不符合条件,则至少会出现编译器错误;忽略它,您可能会得到一个非constexpr
构造函数而没有意识到。In the general case, if you definitely want a constructor to be
constexpr
, though, it may be wise to leave the keyword in so that you at least get a compiler error if it does not meet the criteria; leaving it out, you may get a non-constexpr
constructor without realising it.这篇关于我应该将编译器生成的构造函数标记为constexpr吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!