Libftpp
A modern C++ library
Pool< TType > Class Template Reference

Pool of reusable memory. More...

#include <pool.hpp>

Classes

class  Object
 Wrapper around a TType object managed by the Pool. Provides access to the underlying TType object. More...
 

Public Member Functions

 Pool (size_t size=0)
 
 ~Pool ()
 
void resize (size_t numberOfObjectStored)
 Pre-allocates memory for a given number of objects. More...
 
template<typename... TArgs>
Objectacquire (TArgs &&... p_args)
 Acquires an object from the pool. More...
 
void release (Object &obj)
 Releases an object back into the pool. Destroys the contained TType object and return its slot to the available Stack. More...
 

Detailed Description

template<typename TType>
class Pool< TType >

Pool of reusable memory.

RAII is used to manage the lifetime of objects.

The Pool pre-allocates objects of type TType and reuses them to avoid frequent allocations and deallocations.

Warning
If you resize the pool, all existing objects are destroyed.
Template Parameters
TTypeType of objects managed by the pool.
Pool<MyClass> pool(10); // Create a pool with 10 pre-allocated MyClass objects
auto& obj1 = pool.acquire(arg1, arg2); // Acquire an object from the pool
obj1->doSomething();
pool.release(obj1); // Release the object back to the pool
Pool of reusable memory.
Definition: pool.hpp:37

Definition at line 36 of file pool.hpp.

Constructor & Destructor Documentation

◆ Pool()

template<typename TType >
Pool< TType >::Pool ( size_t  size = 0)

◆ ~Pool()

template<typename TType >
Pool< TType >::~Pool ( )

Member Function Documentation

◆ acquire()

template<typename TType >
template<typename... TArgs>
Object& Pool< TType >::acquire ( TArgs &&...  p_args)

Acquires an object from the pool.

Constructs a new TType object in pre-allocated memory and returns a wrapper Object to access it.

Template Parameters
TArgsTypes of constructor arguments for TType.
Parameters
p_argsArguments forwarded to TType's constructor.
Returns
A Pool::Object wrapper containing the allocated TType.
Exceptions
std::out_of_rangeif no objects are available in the pool.

◆ release()

template<typename TType >
void Pool< TType >::release ( Object obj)

Releases an object back into the pool. Destroys the contained TType object and return its slot to the available Stack.

◆ resize()

template<typename TType >
void Pool< TType >::resize ( size_t  numberOfObjectStored)

Pre-allocates memory for a given number of objects.

Parameters
numberOfObjectStoredNumber of objects to pre-allocate.