简体   繁体   中英

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?

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.

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

Eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM