How can we dynamically allocate at compile time? Does the constexpr
operator new
just allocate memory on the stack?
Asked
Active
Viewed 3,821 times
7

Tachi
- 489
- 8
- 16
-
3Point 22 in [this constant expression reference](https://en.cppreference.com/w/cpp/language/constant_expression) seems relevant. – Some programmer dude Jun 16 '20 at 08:46
-
1related (not sure if still up-to-date) https://stackoverflow.com/questions/53419133/constexpr-operator-new – 463035818_is_not_an_ai Jun 16 '20 at 08:47
-
please clarify, what do you mean with "the `constexpr operator new`" ? – 463035818_is_not_an_ai Jun 16 '20 at 08:48
-
@idclev463035818 my question was wrong, as I misunderstood the meaning of "dynamic allocations" (or, better, the use of the operator new) in a `constexpr` context. The accepted answer clarified everything – Tachi Jun 24 '20 at 14:32
2 Answers
15
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.

Nicolas Dusart
- 1,867
- 18
- 26
7
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

Caleth
- 52,200
- 2
- 44
- 75