Tachi
Tachi

Reputation: 617

How does constexpr new allocate memory?

How can we dynamically allocate at compile time? Does the constexpr operator new just allocate memory on the stack?

Upvotes: 7

Views: 6403

Answers (2)

Caleth
Caleth

Reputation: 63117

It doesn't allocate at all. The compiler evaluates the result of a function that includes allocation and deallocation in calculating it's result.

E.g.

constexpr int triangle_number(int n)
{
    std::vector<int> intermediate(n + 1);
    std::iota(intermediate.begin(), intermediate.end(), 0);
    return std::accumulate(intermediate.begin(), intermediate.end(), 0);
}

std::array<int, triangle_number(5)> arr; // compiler somehow produces 15

Upvotes: 9

Nicolas Dusart
Nicolas Dusart

Reputation: 2007

There is no constexpr new operator.

Since C++20, you can use new operator in constexpr expressions in the condition that you only use a replaceable global allocation function (it means that you don't use a placement new or user-defined allocation function) and that you deallocate the data in the same expression.

So, in your final program, this does not allocate memory, since you end up just with the final result of your constexpr expression.

Upvotes: 16

Related Questions