(PMR)
- namespace
std::pmr
polymorphic_allocator
polymorphic_memory_resource
s- Containers
std::vector<T, std::allocator<T>>
is a different type from
std::vector<T, MyAlloc<T>>
(or any other std
container)
- New in C++17
- Type erasure for allocators
- Virtual call to alloc/dealloc
#include <memory_resource>
- Wrapper around a memory resource
- Allocates a pointer or contructs object
- Move-only
- Convertable from any
T
to anyU
- Comparable
==
,!=
- Abstract base class
- Not templated
- Small interface
- do_allocate, do_deallocate, is_equal
class memory_resource {
public:
virtual memory_resouce() = default;
void* allocate(std::size_t bytes, std::size_t alignment = /*...*/);
void deallocate(void* p, std::size_t bytes, std::size_t alignment = /*...*/);
bool is_equal(const memory_resource& other) const noexcept;
private:
virtual void* do_allocate(std::size_t bytes, std::size_t alignment) = 0;
virtual void do_deallocate(void* p, std::size_t bytes, std::size_t alignment) = 0;
virtual bool do_is_equal(const std::pmr::memory_resource& other) const noexcept = 0;
}
new_delete_resource()
null_memory_resource()
get_default_resource()
,set_default_resource()
synchronized_pool_resource
unsynchronized_pool_resource
monotonic_buffer_resource
demo1.cpp
Now change to std::pmr::vector<>
std::pmr::
variant ofstd
containers with allocators- vector, list, deque, ...
- set, map, unordered_*, ...
namespace std::pmr {
template <typename T>
using vector = ::std::vector<T,
::std::pmr::polymorphic_allocator>;
}
demo1b.cpp
- std containers will automatically propagate allocators
- also std functions
allocate_shared()
- see
std::uses_allocator
- simplified for user code with C++20
std::make_obj_using_allocator