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) ...

Get Mastering the C++17 STL now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.