C++ Logo

std-proposals

Advanced search

[std-proposals] Consteval persistent memory allocator

From: Григорий Шуренков <grigorij1981_at_[hidden]>
Date: Sat, 11 Nov 2023 13:03:09 +0200
Hi!

Currently it is possible to allocate memory during constexpr evaluation,
but such an allocation may not escape constant expression. And the reason
is that if we allow it to escape, it would be rather difficult to
distinguish between memory that needs reclamation and memory that does not
need it, for example:

 constexpr unique_ptr<unique_ptr<int>> uui =
make_unique<unique_ptr<int>(make_unique<int>());

int main() { unique_ptr& ui = *uui; ui.reset(); }

(example from p1974r0 that proposes propconst keyword to distinguish truly
immutable constant values)

However, it seems to me if we have a guarantee in the type, that it may
only point to memory that does not need to be freed, then we can allow a
value of such type to live beyond compile time. Such guarantee can be
provided by a custom allocator (consteval_allocator) with magic allocate
function designated consteval, and deallocate function doing nothing (at
least in runtime).

Then we can allow constexpr values of types like vector<int,
consteval_allocator<int>> or vector<consteval_string,
consteval_allocator<consteval_string>>.

There might be some hidden rocks in this approach, but to me it looks like
a rather small addition to the language that nevertheless makes constexpr
programming a little bit more pleasing than it is now.

Regards,
Gregory

Received on 2023-11-11 11:03:20