Defining a heap with memory_resource
Recall that on resource-constrained platforms, we might not be permitted to use "the heap" (for example via new
and delete
), because the platform's runtime might not support dynamic memory allocation. But we can make our own little heap--not "the heap," just "a heap"--and simulate the effect of dynamic memory allocation by writing a couple of functions allocate
and deallocate
that reserve chunks of a big statically allocated array of char
, something like this:
static char big_buffer[10000]; static size_t index = 0; void *allocate(size_t bytes) { if (bytes > sizeof big_buffer - index) { throw std::bad_alloc(); } index += bytes; return &big_buffer[index - bytes]; } void deallocate(void *p, size_t bytes) { // drop it on the floor }
To keep the code as simple as possible, I made deallocate
a no-op. This little heap allows the caller to allocate up to 10,000 bytes of memory, and then starts...