C++23: Allocator Related Changes -- Sandor Dargo

SANDOR_DARGO_ROUND.JPGIn 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 of T on the heap. While allocate returns a single pointer to the beginning of the allocated memory, allocate_at_least returns a new struct called allocation_result which has two members, the “usual” pointer to the beginning of the allocated memory (ptr) and the number of Ts memory got allocated for (count). count must be at least as large as the input parameter n, but it can also be more.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.