Search code examples
c++c++14

Constexpr with new operator


I use C++14, can I use constexpr like that:

constexpr Myclass* obj = new Myclass()

I get some compilation errors, also tried to google but all examples without dynamic allocation.


Solution

  • I use C++14, can I use constexpr like that:

    No you can't. Evaluation of a new expression in a constant expression is never allowed in C++14.

    In C++20 it is to some degree, but only if you dealloate the allocated memory properly before the constant expression ends. In your example the intended constant expression is the initialization of obj which does not include any deallocation of the allocated memory.