Template Class FirstFitAllocator
Defined in File first_fit_allocator.hpp
-
template<class T>
class FirstFitAllocator Template memory management class using first-fit allocation strategy.
This class pre-allocates memory for a given type and allows acquiring chunks of memory and releasing them efficiently. Only the allocate() function performs memory allocation; other functions use a constant amount of stack memory.
The allocator uses the FirstFitAllocatorBase for efficient memory management with logarithmic time complexity for acquire and release operations.
- Template Parameters
T – Type of elements that will be stored in the allocated memory.
Public Types
-
template<typename E>
using expected_t = expected<E, FirstFitAllocatorBase::Error> Expected type used by this class.
-
using unexpected_t = unexpected<FirstFitAllocatorBase::Error>
Unexpected type used by this class.
Public Functions
-
FirstFitAllocator() = default
Default constructor.
-
inline expected_t<int32_t> allocate(const int32_t size, const int chunk_size = 1)
Allocate memory to handle requests for chunks of a given total size.
Pre-allocates memory that can be divided into chunks for later acquisition. The total memory allocated will be approximately sizeof(T) * size + 32 * size / chunk_size bytes.
- Parameters
size – Total number of elements of type T to support.
chunk_size – Minimum chunk size. Memory will always be allocated in multiples of this size. This can improve allocation speed but reduces control over exact allocated size.
- Returns
Total number of elements that can be managed on success, error on failure. Error::kAlreadyInUse if already initialized, Error::kInvalidSize for invalid parameters, Error::kOutOfMemory if memory allocation fails.
-
inline expected_t<std::pair<T*, int32_t>> acquire(const int32_t size)
Acquire a contiguous block of memory of the specified size.
If a suitable contiguous block exists, returns a pointer to that block and the actual size acquired. The actual size will be the smallest multiple of chunk_size that is greater than or equal to the requested size.
- Parameters
size – Number of elements of type T to acquire.
- Returns
Pair containing pointer to the allocated block and actual number of elements acquired on success, Error::kOutOfMemory if no suitable block exists.
-
inline expected_t<void> release(const T *ptr)
Release a previously acquired block of memory.
The pointer must have been returned by a previous call to acquire(). Once released, the memory becomes available for future acquisitions. A block cannot be released twice.
- Parameters
ptr – Pointer to the memory block to release.
- Returns
Success or error status. Error::kBlockNotAllocated if the pointer was not previously acquired or is invalid.