.. _program_listing_file_Source_Common_Inc_Memory_PoolAllocator.h: Program Listing for File PoolAllocator.h ======================================== |exhale_lsh| :ref:`Return to documentation for file ` (``Source\Common\Inc\Memory\PoolAllocator.h``) .. |exhale_lsh| unicode:: U+021B0 .. UPWARDS ARROW WITH TIP LEFTWARDS .. code-block:: cpp #pragma once #include #include #include "Types.h" namespace Azura { template struct PoolNode { T mData; PoolNode* pNext{nullptr}; }; template class PoolAllocator { using Node = PoolNode; public: PoolAllocator(U32 totalElements); ~PoolAllocator(); T* allocate(); void deallocate(T* data); private: U32 mCount; Node* pHead; Node* pTail; void* pMemory; }; template PoolAllocator::PoolAllocator(U32 totalElements) : mCount(totalElements) { pMemory = malloc(sizeof(Node) * mCount); pHead = (Node*)pMemory; Node* itr = pHead; Node* prev = nullptr; // Form Initial Links between Nodes for (auto i = 0U; i < mCount; i++) { itr->pNext = nullptr; if (prev != nullptr) { prev->pNext = itr; } prev = itr; itr++; } pTail = prev; } template PoolAllocator::~PoolAllocator() { free(pMemory); } template T* PoolAllocator::allocate() { T* result = nullptr; if (pHead != nullptr) { result = reinterpret_cast(pHead); auto oldNode = pHead; pHead = pHead->pNext; oldNode->pNext = nullptr; if (pHead == nullptr) { pTail = nullptr; } } return result; } template void PoolAllocator::deallocate(T* data) { Node* node = reinterpret_cast(data); if (pTail != nullptr) { pTail->pNext = node; } else { pHead = node; } pTail = node; } } // namespace Azura