23namespace deluge::memory {
28template <
typename T,
template <
typename>
typename Alloc = std::allocator>
30 static constexpr size_t kDefaultSize = 48;
37 ~ObjectPool() {
clear(); };
41 static constexpr ObjectPool&
get() {
42 static thread_local ObjectPool instance;
50 if (capacity_ < objects_.size()) {
52 while (objects_.size() > capacity_) {
53 alloc_.deallocate(objects_.top(), 1);
61 [[nodiscard]]
size_t capacity()
const {
return capacity_; }
65 [[nodiscard]]
size_t size()
const {
return objects_.size(); }
72 ObjectPool& op =
get();
73 if (op.objects_.size() < op.capacity_) {
74 op.objects_.push(obj);
77 Alloc<T>().deallocate(obj, 1);
84 for (
size_t i = objects_.size(); i < capacity_; ++i) {
85 objects_.push(alloc_.allocate(1));
97 template <
typename... Args>
100 if (objects_.empty()) {
101 obj = alloc_.allocate(1);
104 obj = objects_.top();
107 return {
new (obj) T(std::forward<Args>(args)...), &
recycle};
112 while (!objects_.empty()) {
113 alloc_.deallocate(objects_.top(), 1);
120 [[nodiscard]]
constexpr bool empty()
const {
return objects_.empty(); }
123 size_t capacity_ = kDefaultSize;
124 std::stack<T*, std::vector<T*, Alloc<T*>>> objects_;
void clear()
Clears the pool.
Definition object_pool.h:111
void resize(size_t n)
Sets the size of the pool.
Definition object_pool.h:48
size_t size() const
Gets the number of objects in the pool.
Definition object_pool.h:65
pointer_type acquire(Args &&... args) noexcept(false)
Acquires an object from the pool.
Definition object_pool.h:98
size_t capacity() const
Gets the capacity of the pool.
Definition object_pool.h:61
T value_type
The type of object in the pool.
Definition object_pool.h:35
void repopulate() noexcept(false)
Repopulates the pool to its original size.
Definition object_pool.h:83
static constexpr ObjectPool & get()
Gets the global pool for a given object.
Definition object_pool.h:41
std::unique_ptr< T, decltype(&recycle)> pointer_type
A managed pointer type for an object from the pool.
Definition object_pool.h:90
static void recycle(gsl::owner< T * > obj)
Definition object_pool.h:69
constexpr bool empty() const
Checks if the pool is empty.
Definition object_pool.h:120