template <class T>
class MemoryPool
{
public:
MemoryPool(size_t size=EXPANSION_SIZE)
{
expandTheFreeList(size);
}
~MemoryPool()
{
MemoryPool<T>*nextPtr=next;
while(nextPtr)
{
delete [] nextPtr;
nextPtr=next->next;
}
}
void *alloc(size_t size)
{
if(!next)
{
expandTheFreeList();
}
MemoryPool<T>*head=next;
next=head->next;
return head;
}
void free(void *doomed)
{
MemoryPool<T>*head=static_cast<MemoryPool<T>*>doomed;
head->next=next;
next=head;
}
private:
MemoryPool<T>*next;
enum {EXPANSION_SIZE = 32};
void expandTheFreeList(int howMany=EXPANSION_SIZE)
{
size_t size=(sizeof(T)>sizeof(MemoryPool<T>*))?sizeof(T):sizeof(MemoryPool<T>*);
MemoryPool<T>*runner=static_cast<MemoryPool<T>*>new char [size] ;
next=runner;
for(int i=0;i<howMany;i++)
{
runner->next=static_cast<MemoryPool<T>*>new char[size];
runner=runner->next;
}
runner->next=NULL;
}
};
内存管理 freelist
最新推荐文章于 2022-09-25 16:19:37 发布