Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose and usage of `memory_resource`?

The standard C++17 include a new namespace pmr including a set of classes grouped under the name of memory_resource.

After a search on internet, I found very few vulgarized information about it, the direct consequence is this question:

What are the main ideas behind pmr and especially pmr::memory_resource?


Detailing a bit more the question, some of the question marks in my head are:

  • What does it bring new, or what were the limitations it solve?
  • What is the difference with allocator?
  • Does polymorphic mean it is possible to select runtime the allocator provided to a container constructor? (e.g. for testing purpose)
  • Does it helps for implementing memory pool, or other memory management schemes?

Context:

In the intend of creating a memory pool allocator, I found information about this namespace. Reading names like pool_options or polymorphic_allocator raised my attention.


Related questions:

polymorphic_allocator: when and why should I use it?

like image 826
Adrian Maire Avatar asked Jun 28 '17 09:06

Adrian Maire


People also ask

What is std pmr?

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.

What is namespace PMR?

namespace pmr { template <class T> using vector = std::vector<T, polymorphic_allocator<T>>; } // namespace pmr. The standard library containers (except std::array) are constructed in such a way that the functions for allocating and freeing memory are encapsulated in an allocator which is passed as a template parameter.


1 Answers

A polymorphic_allocator is intended to let you have an allocator whose behavior is dynamically determined at runtime.

The only way to create a polymorphic_allocator is:

  1. Default constructed, in which case it uses std::pmr::get_default_resource() return value, which is a memory_resource*.

  2. Pass it a memory_resource*.

  3. copy from another polymorphic_allocator.

So the point of customization for a polymorphic_allocator is creating a class that inherits from memory_resource and implementing its methods, or using one of the pre-declared memory_resources that are defined in std::pmr: (un)synchronized_pool_resource and monotonic_buffer_resource as types, or std::pmr::new_delete_resource() / std::pmr::null_memory_resource().

Suppose you want a your memory to be allocated using a strategy different than the 5 provided in std::pmr. Then you make a class that inherits from std::pmr::memory_resource, and pass it to a container which uses a polymorphic_allocator.

like image 169
Yakk - Adam Nevraumont Avatar answered Sep 21 '22 22:09

Yakk - Adam Nevraumont