In this post, we are going to review two changes related to allocators in C++. One is about providing size information about the allocated memory and the other is about how CTAD should happen for containers with non-default allocators.
C++23: Allocator Related Changes
by Sandor Dargo
From the article:
P0401R6 gives a new way to allocate memory on the heap to limit spurious reallocations.
The new interface of
std::allocator
looks like this, but there is also a free function version of it.template<class Pointer> struct allocation_result { Pointer ptr; size_t count; }; // this class already exist: namespace std { template<class T> class allocator { public: // lots of existing things // ... // this is the old way to allocate [[nodiscard]] constexpr T* allocate(size_t n); // and this is the new way [[nodiscard]] constexpr allocation_result<T*> allocate_at_least(size_t n); // the interface for deallocation does not change constexpr void deallocate(T* p, size_t n); }; }As you can see,allocate_at_least
takes a number and it should allocate enough memory for at least that many instances ofT
on the heap. Whileallocate
returns a single pointer to the beginning of the allocated memory,allocate_at_least
returns a newstruct
calledallocation_result
which has two members, the “usual” pointer to the beginning of the allocated memory (ptr
) and the number ofT
s memory got allocated for (count
).count
must be at least as large as the input parametern
, but it can also be more.
Add a Comment
Comments are closed.