Skip to content

Memory resources

Memory resources

The class std::pmr::memory_resource is an abstract interface to an unbounded set of classes encapsulating memory resources. The class template std::pmr::polymorphic_allocator is an Allocator which exhibits different allocation behavior depending upon the std::pmr::memory_resource from which it is constructed. This allows us to control how a given container allocates memory.

Since memory_resource uses runtime polymorphism to manage allocations, different container instances with polymorphic_allocator as their static allocator type are interoperable, but can behave as if they had different allocator types.

Not all compilers implement PMR yet, even though it's a C++17 feature. We need a CMake script such as FindPMR.cmake to identify if your compiler implements it. Another option is using __has_include to identify if the appropriate headers are available.

1
2
3
4
5
6
find_package(PMR)
if (PMR_FOUND)
    add_executable(memory_resource memory_resources.cpp)
else ()
    message("Your compiler does not support *PMR* yet")
endif ()

1
#include <memory_resource>

1
2
3
char buffer[64] = {}; // a small buffer on the stack
std::fill_n(std::begin(buffer), std::size(buffer) - 1, '_');
std::cout << buffer << '\n';

1
2
std::pmr::monotonic_buffer_resource pool{std::data(buffer),
                                         std::size(buffer)};

1
2
3
4
5
std::pmr::vector<char> vec{&pool};
for (char ch = 'a'; ch <= 'z'; ++ch) {
    vec.push_back(ch);
}
std::cout << buffer << '\n';

1
2
3
4
5
std::pmr::unsynchronized_pool_resource pool2;
std::pmr::vector<char> vec2{&pool2};
for (char ch = 'a'; ch <= 'z'; ++ch) {
    vec2.push_back(ch);
}

Share Snippets