// TemplateCBlockAlloc.h: interface for the CBlockAlloc class. // ////////////////////////////////////////////////////////////////////// #ifndef _TEMPLATE_COBJECTALLOCATOR_H #define _TEMPLATE_COBJECTALLOCATOR_H #if defined _MT || defined _REENTRANT # define USE_ALLOCATOR_MUTEX #endif #include #include "Types.h" #include "Mutex.h" #ifdef EXTERNAL_DISTRO namespace NAMESPACE { #endif namespace Base { const uint32 MAX_BLOCK_COUNT = 32; template class CObjectAllocator { public: CObjectAllocator(uint32 size=32) { if (size < 32) size = 32; for (uint32 index=0; indexnext; new (node) TYPE; mObjectCount++; #ifdef USE_ALLOCATOR_MUTEX mMutex.Unlock(); #endif return (TYPE *)node; } TYPE *Construct(const TYPE& object) { #ifdef USE_ALLOCATOR_MUTEX mMutex.Lock(); #endif if (!mUnusedList) Allocate(mObjectCount); Node *node = mUnusedList; mUnusedList = mUnusedList->next; new (node) TYPE(object); mObjectCount++; #ifdef USE_ALLOCATOR_MUTEX mMutex.Unlock(); #endif return (TYPE *)node; } void Destroy(TYPE *object) { if (object == NULL) return; #ifdef USE_ALLOCATOR_MUTEX mMutex.Lock(); #endif object->~TYPE(); Node *node = reinterpret_cast(object); node->next = mUnusedList; mUnusedList = node; mObjectCount--; #ifdef USE_ALLOCATOR_MUTEX mMutex.Unlock(); #endif } TYPE *FastConstruct() { if (!mUnusedList) Allocate(mObjectCount); Node *node = mUnusedList; mUnusedList = mUnusedList->next; new (node) TYPE; mObjectCount++; return (TYPE *)node; } TYPE *FastConstruct(const TYPE& object) { if (!mUnusedList) Allocate(mObjectCount); Node *node = mUnusedList; mUnusedList = mUnusedList->next; new (node) TYPE(object); mObjectCount++; return (TYPE *)node; } void FastDestroy(TYPE *object) { if (object == NULL) return; object->~TYPE(); Node *node = reinterpret_cast(object); node->next = mUnusedList; mUnusedList = node; mObjectCount--; } private: struct Node { char buffer[sizeof(TYPE)]; Node* next; }; bool Allocate(uint32 size) { if (mMemoryBlockCount == MAX_BLOCK_COUNT) return false; Node* newMemoryBlock = new Node[size]; mBytesAllocated += size * sizeof(Node); for (uint32 i=0; i