C ++ 14:你能在constexpr中调用new吗? [英] C++14: can you call new in a constexpr?
问题描述
当C ++ 14取消对 constexpr
的限制时,它似乎包含以下内容(从 Wikipedia ):
When C++14 lifted restrictions on constexpr
it seemed to include the following (copied from Wikipedia):
表达式可能会更改对象,如果
对象的生命周期在常量表达式函数内开始。这包括
调用任何非const constexpr声明的非静态成员函数。
Expressions may change the value of an object if the lifetime of that object began within the constant expression function. This includes calls to any non-const constexpr-declared non-static member functions.
这似乎意味着你可以使用 new
创建一个对象,只要你在表达式中 delete
,它就会被允许。 / p>
That seems to imply that you could create an object using new
and as long as you delete
it within the expression, then it would be allowed.
推荐答案
语言律师的答案。所有对 N3797 的引用。
Language lawyer answer. All references to N3797.
7.1.5 / 5说明:
7.1.5/5 states:
对于非模板,非默认
constexpr
函数或非模板非默认的非继承constexpr
构造函数,如果没有参数值,函数或构造函数可以是核心常量表达式(5.19)的求值子表达式,程序是不成形的;
For a non-template, non-defaulted
constexpr
function or a non-template, non-defaulted, non-inheritingconstexpr
constructor, if no argument values exist such that an invocation of the function or constructor could be an evaluated subexpression of a core constant expression (5.19), the program is ill-formed; no diagnostic required.
跳转到5.19,我们看到:
Jumping over to 5.19, we see:
A 条件表达式
e
是一个核心常量表达式 c $ c> e 遵循抽象机(1.9)的规则,将评估以下表达式之一:
A conditional-expression
e
is a core constant expression unless the evaluation ofe
, following the rules of the abstract machine (1.9), would evaluate one of the following expressions:
-
... [lot of bullets] ...
... [lots of bullets]...
4);
a delete-expression (5.3.5);
a delete-expression (5.3.5);
... [lot more bullets] ...
... [lots more bullets]...
So no:包含 constexpr
函数的程序,其中包含 new
或 delete
在它是形式不好,不需要诊断。 (我会感到惊讶,但是,如果任何半满的编译器无法诊断
新
或删除
的实例a constexpr
函数,必需或不需要。)
So no: a program containing a constexpr
function with a new
or delete
in it is ill-formed, no diagnostic required. (I'd be surprised, however, if any half-decent compiler failed to diagnose instances of new
or delete
in a constexpr
function, required or not.)
这篇关于C ++ 14:你能在constexpr中调用new吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!