Better_Software_Header_Mobile Better_Software_Header_Web

Find what you need - explore our website and developer resources

A guide to polymorphic memory allocators in C++

Part 1: an introduction to the mechanics of C++17's std::pmr

Animation demonstrating how a free list allocator allocates and deallocates memory

Animation demonstrating how a block allocator allocates and deallocates memory

Animation demonstrating how an arena allocator allocates and deallocates memory

namespace std::pmr {
template <typename T>
using vector = std::vector<T, polymorphic_allocator<T>>;
}
struct memory_resource
{
    virtual void* do_allocate(size_t bytes, size_t align) = 0;
    virtual void do_deallocate(void* memory, size_t bytes, size_t align) = 0;
};

template <typename T>
struct polymorphic_allocator
{
    memory_resource* ptr = std::pmr::get_default_resource();

    polymorphic_allocator(memory_resource* mr) : ptr(mr) {}

    T* allocate()
    {
        return static_cast<T*>(ptr->do_allocate(sizeof(T), alignof(T)));
    }

    void deallocate(T* object)
    {
        ptr->do_deallocate(object, sizeof(T), alignof(T));
    }
};
// A program which generates many random sentences and then sorts them alphabetically
std::string randomWord(size_t wordLength)
{
    std::string out;
    for (size_t i = 0; i < wordLength; ++i) {
        constexpr uint8_t start = 'a';
        constexpr uint8_t numLetters = ('z' - start) + 1;
        out.push_back(char((rand() % numLetters) + start));
    }
    return out;
}

std::list<std::string> randomSentence(size_t numWords)
{
    std::list<std::string> out;
    for (size_t i = 0; i < numWords; ++i)
        out.emplace_back(randomWord((rand() % 10) + 15) + " ");
    return out;
}

int main()
{
    constexpr size_t numSentences = 5000000;
    std::vector<std::list<std::string>> sentences;

    srand(42);

    for (size_t i = 0; i < numSentences; ++i)
        sentences.emplace_back(randomSentence((rand() % 15) + 5));

    std::stable_sort(sentences.begin(), sentences.end());

    std::string lastSentenceJoined = std::accumulate(
        sentences.back().begin(), sentences.back().end(), std::string{});
    std::printf("Last sentence alphabetically: %s\n", lastSentenceJoined.c_str());
}
Last sentence alphabetically: zzzzusslypcugzacuchocbl ghmojccoybpjptwld elitxsybwusezdvjwuuk hfxosxxsasomuanvrskilu uypkgyrcxrkjfik mpwtoritoexuoezxey qdadywsquoxeeuhnpg legucxktyokhrmrelrovr pwlviepruvncdbgt jfcjbthjwndwxkdcuxophky ljwulcqrnwesihtleoetocv xhuzqiuiqtrmjaxbw dtvomfnbvxsbtqndeblb bnxpfgrjyhuemyxbvgr tgoxwqntiolmgedajnqnijnl naelauomoggyjdt
// A program which generates many random sentences and then sorts them alphabetically
std::pmr::string randomWord(size_t wordLength)
{
    std::pmr::string out;
    for (size_t i = 0; i < wordLength; ++i) {
        constexpr uint8_t start = 'a';
        constexpr uint8_t numLetters = ('z' - start) + 1;
        out.push_back(char((rand() % numLetters) + start));
    }
    return out;
}

std::pmr::list<std::pmr::string> randomSentence(size_t numWords)
{
    std::pmr::list<std::pmr::string> out;
    for (size_t i = 0; i < numWords; ++i)
        out.emplace_back(randomWord((rand() % 10) + 15) + " ");
    return out;
}

int main()
{
    constexpr size_t numSentences = 5000000;
    std::pmr::vector<std::pmr::list<std::pmr::string>> sentences;

    srand(42);

    for (size_t i = 0; i < numSentences; ++i)
        sentences.emplace_back(randomSentence((rand() % 15) + 5));

    std::stable_sort(sentences.begin(), sentences.end());

    std::pmr::string lastSentenceJoined = std::accumulate(sentences.back().begin(), sentences.back().end(), std::pmr::string{});
    std::printf("Last sentence alphabetically: %s\n", lastSentenceJoined.c_str());
}
std::pmr::monotonic_buffer_resource arena;
std::pmr::set_default_resource(&arena);
int main()
{
    std::pmr::monotonic_buffer_resource arena;

    constexpr size_t numSentences = 5000000;
    std::pmr::vector<std::pmr::list<std::pmr::string>> sentences{&arena};

    // ...
sentences.emplace_back(randomSentence((rand() % 15) + 5));
std::pmr::list<std::pmr::string>
randomSentence(std::pmr::polymorphic_allocator<> allocator, size_t numWords)
{
    std::pmr::list<std::pmr::string> out{allocator};
    // ...
sentences.emplace_back(&arena, randomSentence((rand() % 15) + 5));
std::pmr::string randomWord(size_t wordLength)
{
    // we build a string using the new/delete resource
    std::pmr::string out;
    for (size_t i = 0; i < wordLength; ++i) {
        constexpr uint8_t start = 'a';
        constexpr uint8_t numLetters = ('z' - start) + 1;
        out.push_back(char((rand() % numLetters) + start));
    }
    // we return a string which still has a pointer to the new/delete resource
    return out;
}

std::pmr::list<std::pmr::string>
randomSentence(std::pmr::polymorphic_allocator<> allocator, size_t numWords)
{
    std::pmr::list<std::pmr::string> out{allocator};
    for (size_t i = 0; i < numWords; ++i)
        // right here, we have to copy the characters from randomWord into a piece
        // of memory allocated by `allocator`, since that's what the `out` string
        // uses.
        out.emplace_back(randomWord((rand() % 10) + 15) + " ");
    return out;
}
std::pmr::string
randomWord(std::pmr::polymorphic_allocator<> allocator, size_t wordLength)
{
    std::pmr::string out{allocator};
    for (size_t i = 0; i < wordLength; ++i) {
        constexpr uint8_t start = 'a';
        constexpr uint8_t numLetters = ('z' - start) + 1;
        out.push_back(char((rand() % numLetters) + start));
    }
    return out;
}

std::pmr::list<std::pmr::string>
randomSentence(std::pmr::polymorphic_allocator<> allocator, size_t numWords)
{
    std::pmr::list<std::pmr::string> out{allocator};
    std::pmr::monotonic_buffer_resource tempArena; // this is new!
    for (size_t i = 0; i < numWords; ++i)
        // pass `tempArena` as what `randomWord()` should allocate with, but
        // copy it out into a container that uses `allocator` instead, so we can
        // return it out of this function.
        out.emplace_back(randomWord(&tempArena, (rand() % 10) + 15) + " ");
    return out;
}
std::pmr::string randomWord(size_t wordLength)
{
    std::pmr::monotonic_buffer_resource tempArena;
    std::pmr::string out{&tempArena};
    for (size_t i = 0; i < wordLength; ++i) {
        constexpr uint8_t start = 'a';
        constexpr uint8_t numLetters = ('z' - start) + 1;
        out.push_back(char((rand() % numLetters) + start));
    }
    // Undefined behavior: this returns the string `out`, which contains a
    // pointer to a stack-local variable `tempArena`, as well as memory
    // allocated from it.
    return out;
}
std::pmr::string
randomWord(std::pmr::polymorphic_allocator<> allocator, size_t wordLength);
class FooFactory
{
private:
    std::pmr::monotonic_buffer_resource m_resource;
    std::pmr::polymorphic_allocator<std::byte> m_allocator{&m_resource};
public:
    void configureFooField(int num);
    // this new_object() member function is C++20 only, included for brevity
    Foo* makeFoo() { return m_allocator.new_object<Foo>(); }

    // though it is not obvious to the caller, all Foo*s MUST no longer be in
    // use when this object is destroyed, otherwise that is use-after-free.
    ~FooFactory() = default;
};
explicit FooFactory(std::pmr::polymorphic_allocator<std::byte> a)
    : m_allocator(a)
{}
{
    // BEFORE...
    FooFactory factory;
    factory.configureFooField(42);
    Foo* myFoo = factory.makeFoo();
    return myFoo; // use-after-free when someone else dereferences this...
}
{
    // AFTER...
    std::pmr::monotonic_buffer_resource arena;

    FooFactory factory{&arena};
    factory.configureFooField(42);
    Foo* myFoo = factory.makeFoo();

    // hm... I probably shouldn't do this, since `factory` uses the `arena`.
    // Maybe if the caller wants to access this `Foo*`, they should pass me a
    // polymorphic_allocator, which I can give to the `FooFactory`, as was
    // recommended in best practice #1?
    //    - The person writing this
    return myFoo;
}
std::pmr::vector<std::pmr::vector<std::pmr::string>> spreadsheet;
std::pmr::monotonic_buffer_resource tempArena;

for (size_t x = 0; x < dimensions.x; ++x) {
    std::pmr::vector<std::pmr::string> column{&tempArena};

    for (size_t y = 0; y < dimensions.y; ++y) {
        std::pmr::string tempString{&tempArena};

        fillLineForSpreadsheetCell(tempString, x, y); // hypothetical function
        column.emplace_back(std::move(tempString));

        // Undefined behavior: got too greedy with memory usage optimization, called this too
        // early, now `column` is a dangling reference
        tempArena.release();
    }

    spreadsheet.push_back(std::move(column));
}
std::pmr::vector<std::pmr::vector<std::pmr::string>> spreadsheet;

for (size_t x = 0; x < dimensions.x; ++x) {
    std::pmr::monotonic_buffer_resource tempArena; // no need to call .release(), this gets destroyed at the right time
    auto column = std::pmr::vector<std::pmr::string>{&tempArena};

    for (size_t y = 0; y < dimensions.y; ++x) {
        std::pmr::string tempString{&tempArena};

        fillLineForSpreadsheetCell(tempString, x, y); // hypothetical function
        column.emplace_back(std::move(tempString));
    }

    spreadsheet.push_back(std::move(column));
}
void myFunction(std::pmr::polymorphic_allocator<> allocator) {
    // just don't do this, please.
    static const std::pmr::anything_pmr_at_all varname{allocator};
}