22namespace deluge::memory {
27template <
typename T,
template <
typename>
typename Alloc = std::allocator>
29 static constexpr size_t kDefaultSize = 48;
36 ~ObjectPool() {
clear(); };
40 static constexpr ObjectPool&
get() {
41 static thread_local ObjectPool instance;
49 if (capacity_ < objects_.size()) {
51 while (objects_.size() > capacity_) {
52 alloc_.deallocate(objects_.top(), 1);
60 [[nodiscard]]
size_t capacity()
const {
return capacity_; }
64 [[nodiscard]]
size_t size()
const {
return objects_.size(); }
71 ObjectPool& op =
get();
72 if (op.objects_.size() < op.capacity_) {
73 op.objects_.push(obj);
76 Alloc<T>().deallocate(obj, 1);
83 for (
size_t i = objects_.size(); i < capacity_; ++i) {
84 objects_.push(alloc_.allocate(1));
96 template <
typename... Args>
99 if (objects_.empty()) {
100 obj = alloc_.allocate(1);
103 obj = objects_.top();
106 return {
new (obj) T(std::forward<Args>(args)...), &
recycle};
111 while (!objects_.empty()) {
112 alloc_.deallocate(objects_.top(), 1);
119 [[nodiscard]]
constexpr bool empty()
const {
return objects_.empty(); }
122 size_t capacity_ = kDefaultSize;
123 std::stack<T*, std::vector<T*, Alloc<T*>>> objects_;
void clear()
Clears the pool.
Definition object_pool.h:110
void resize(size_t n)
Sets the size of the pool.
Definition object_pool.h:47
size_t size() const
Gets the number of objects in the pool.
Definition object_pool.h:64
pointer_type acquire(Args &&... args) noexcept(false)
Acquires an object from the pool.
Definition object_pool.h:97
size_t capacity() const
Gets the capacity of the pool.
Definition object_pool.h:60
T value_type
The type of object in the pool.
Definition object_pool.h:34
void repopulate() noexcept(false)
Repopulates the pool to its original size.
Definition object_pool.h:82
static constexpr ObjectPool & get()
Gets the global pool for a given object.
Definition object_pool.h:40
std::unique_ptr< T, decltype(&recycle)> pointer_type
A managed pointer type for an object from the pool.
Definition object_pool.h:89
static void recycle(gsl::owner< T * > obj)
Definition object_pool.h:68
constexpr bool empty() const
Checks if the pool is empty.
Definition object_pool.h:119