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

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

Expressions can change the value of an object if the lifespan of this object began in the constant expression function. This includes calls for any non-const constexpr-declared non-static member functions.

It looks like you can create an object using new and as long as you delete it inside the expression, then this will be allowed.

+4
source share
2 answers

The answer is a language attorney. All references to N3797 .

7.1.5 / 5 status:

For a non-template, non-default function constexpr or a non-template non-default, which does not inherit the constexpr constructor, if there are no argument values, so the function or constructor call can be an estimated subexpression of the main constant expression (5.19), the program is poorly formed; no diagnostics required.

Passing to 5.19, we see:

The conditional expression e is an expression of the basic constant if the estimate e , following the rules of the abstract machine (1.9), does not evaluate one of the following expressions:

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

  • new expression (5.3.4);

  • delete-expression (5.3.5);

  • ... [more rounds] ...

So, no: the program containing the constexpr function with new or delete is poorly formed in it, no diagnostics are required. (I would be surprised, however, if some semi-decent compiler could not diagnose new or delete instances in the constexpr function, necessarily or not.)

+7
source

I do not think so. You are still limited to calls to other constexpr functions. new is a call to operator new() , which is not a constexpr function. The same goes for delete .

+2
source

Source: https://habr.com/ru/post/1212712/


All Articles