Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++14: can you call new in a constexpr?

When C++14 lifted restrictions on constexpr it seemed to include the following (copied from Wikipedia):

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.

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.

like image 801
Glenn Teitelbaum Avatar asked Feb 20 '14 02:02

Glenn Teitelbaum


People also ask

What can be constexpr in C++?

constexpr indicates that the value, or return value, is constant and, where possible, is computed at compile time. A constexpr integral value can be used wherever a const integer is required, such as in template arguments and array declarations.

Can you modify constexpr?

A const int var can be dynamically set to a value at runtime and once it is set to that value, it can no longer be changed. A constexpr int var cannot be dynamically set at runtime, but rather, at compile time. And once it is set to that value, it can no longer be changed.

Can constexpr functions call non constexpr functions?

A call to a constexpr function produces the same result as a call to an equivalent non- constexpr function , except that a call to a constexpr function can appear in a constant expression. The main function cannot be declared with the constexpr specifier.

Which is false about constexpr?

Short answer: static_assert(false) should never appear in a constexpr if expression, regardless of whether it's in a template function or whether it's in the discarded branch.


1 Answers

Language lawyer answer. All references to N3797.

7.1.5/5 states:

For a non-template, non-defaulted constexpr function or a non-template, non-defaulted, non-inheriting constexpr 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.

Jumping over to 5.19, we see:

A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (1.9), would evaluate one of the following expressions:

  • ... [lots of bullets]...

  • a new-expression (5.3.4);

  • a delete-expression (5.3.5);

  • ... [lots more bullets]...

So no: a program containing a constexpr function with an unconditional invocation of new or delete in it is ill-formed, no diagnostic required. (I'd be surprised, however, if any half-decent compiler failed to diagnose such invocations of new or delete in a constexpr function, required or not.)

like image 103
Casey Avatar answered Sep 22 '22 17:09

Casey