Posted Joe Chu cpp3 minutes read (About 437 words)0 visits
Design An Allocator
Control how memory is allocated and deallocated.
1. Introduction
Custom allocators in C++ allow developers to control how memory is allocated and deallocated, providing opportunities for optimization and resource management tailored to specific needs. The Standard Template Library (STL) uses allocators to manage memory, and by default, it uses std::allocator, but we can provide our own allocator for customized behavior.
voiddeallocate(T* p, std::size_t n)noexcept{ std::cout << "deallocating " << n << " elements of size " << sizeof(T) << ".\n"; ::operatordelete(p); }
// Construct an element of type U at the given memory location template <typename U, typename... Args> voidconstruct(U* p, Args&&... args){ std::cout << "Constructing element.\n"; new (p) U(std::forward<Args>(args)...); }
// Destroy an element of type U at the given memory location template <typename U> voiddestroy(U* p){ std::cout << "Destroying element: " << *p << '\n'; p->~U(); } };
template <typename T, typename Alloc = std::allocator<T>> class Array { public: using allocator_type = Alloc; using value_type = T; using size_type = std::size_t; using pointer = T*; using const_pointer = const T*; using reference = value_type&; using const_reference = const value_type&;
Array(size_type size) : _size(size), _data(_alloc.allocate(_size)), _pos(0){ for (size_type i = 0; i < _size; ++i) { _alloc.construct(_data + i); } }
~Array() { for (size_type i = 0; i < _size; ++i) { _alloc.destroy(_data + i); } _alloc.deallocate(_data, _size); }
voidadd(T&& val){ new (&_data[_pos++]) T(std::move(val)); }
Example 1 Allocator() allocating 3 element(s) of size 32 Constructing element. Constructing element. Constructing element. A B C Destroying element: A Destroying element: B Destroying element: C deallocating 3 elements of size 32. Example 2 allocating 3 element(s) of size 4 Allocator() Constructing element. Constructing element. Constructing element. 1 2 3 Destroying element: 1 Destroying element: 2 Destroying element: 3 deallocating 3 elements of size 4. ~Allocator() ~Allocator()