Polymorphic Allocator

C++ 17 has introduced Polymorphic allocator as an enhancement to the standard allocator from the Standard Library.

Polymorphic Allocator

To be concise, a polymorphic allocator conforms to the rules of an allocator from the Standard Library.

However, at its core, it uses a memory resource object to perform memory management.

Polymorphic Allocator contains a pointer to a memory resource class, and that’s why it can use a virtual method dispatch. You can change the memory resource at runtime while keeping the type of the allocator.

All the types for polymorphic allocators live in a separate namespace std::pmr (PMR stands for Polymorphic Memory Resource), in the <memory_resource> header.

Core elements of pmr:

  • std::pmr::memory_resource - is an abstract base class for all other implementations. It defines the following pure virtual methods: do_allocate, do_deallocate and do_is_equal.
  • std::pmr::polymorphic_allocator - is an implementation of a standard allocator that uses memory_resource object to perform memory allocations and deallocations.
  • global memory resources accessed by new_delete_resource() and null_memory_resource()
  • a set of predefined memory pool resource classes:
    • synchronized_pool_resource
    • unsynchronized_pool_resource
    • monotonic_buffer_resource
  • template specialisations of the standard containers with polymorphic allocator, for example std::pmr::vector, std::pmr::string, std::pmr::map and others. Each specialisation is defined in the same header file as the corresponding container.

Get hands-on with 1400+ tech skills courses.