22 template <class T, std::enable_if_t<std::is_default_constructible<T>::value,
bool> =
true>
26 constexpr
static std::size_t DEFAULT_POOL_SIZE = 100;
27 #pragma push_macro("max")
29 constexpr
static std::size_t INFINITE_POOL_SIZE = std::numeric_limits<std::size_t>::max();
30 #pragma pop_macro("max")
35 explicit DynamicObjectPool(std::size_t maxPoolSize = DEFAULT_POOL_SIZE, std::size_t initialSize = 0)
36 : m_MaxPoolSize(maxPoolSize)
38 if (initialSize > maxPoolSize)
40 throw std::invalid_argument(
"Preallocated objects cannot exceed the maximum pool size");
80 std::unique_lock<std::mutex> lock(m_Mutex);
89 T* obj = m_Pool.top();
113 std::unique_lock<std::mutex> lock(m_Mutex);
115 if (m_MaxPoolSize == INFINITE_POOL_SIZE || m_Pool.size() < m_MaxPoolSize)
130 std::lock_guard<std::mutex> lock(m_Mutex);
131 return m_Pool.size();
137 std::lock_guard<std::mutex> lock(m_Mutex);
138 return m_MaxPoolSize;
144 std::lock_guard<std::mutex> lock(m_Mutex);
148 while (m_Pool.size() > m_MaxPoolSize)
159 std::unique_lock<std::mutex> lock(m_Mutex);
161 if (m_MaxPoolSize < count)
163 throw std::invalid_argument(
"Preallocated objects cannot exceed the maximum pool size");
167 for (std::size_t i = m_Pool.size(); i < count; i++)
169 m_Pool.push(
new T());
176 std::unique_lock<std::mutex> lock(m_Mutex);
177 while (!m_Pool.empty())
185 std::size_t m_MaxPoolSize;
186 mutable std::mutex m_Mutex;
187 std::stack<T*> m_Pool;
A generic object pool implementation.
Definition: ObjectPool.h:24
void releaseObject(std::unique_ptr< T > obj)
Releases a unique pointer to an object back to the pool.
Definition: ObjectPool.h:100
DynamicObjectPool(std::size_t maxPoolSize=DEFAULT_POOL_SIZE, std::size_t initialSize=0)
Definition: ObjectPool.h:35
void clear()
Deallocates and releases all objects currently held by the pool.
Definition: ObjectPool.h:174
void releaseObjectRaw(T *obj)
Releases a raw pointer to an object back to the pool.
Definition: ObjectPool.h:111
std::size_t size() const
Gets the current number of objects in the pool.
Definition: ObjectPool.h:128
~DynamicObjectPool()
A destructor for this class that deletes all objects in the pool.
Definition: ObjectPool.h:56
void setMaxSize(std::size_t maxSize)
Sets the maximum number of objects in the pool.
Definition: ObjectPool.h:142
T * acquireObjectRaw()
Acquires a raw pointer to an object from the pool.
Definition: ObjectPool.h:78
void preallocate(std::size_t count)
Pre-allocates up to a minimum number of objects in the pool.
Definition: ObjectPool.h:157
std::size_t maxSize() const
Gets the maximum number of objects in the pool.
Definition: ObjectPool.h:135
std::unique_ptr< T > acquireObject()
Acquires a unique pointer to an object from the pool.
Definition: ObjectPool.h:67
The main namespace for the PcapPlusPlus lib.