内存管理 freelist

template 
class MemoryPool
{
public:
    MemoryPool(size_t size=EXPANSION_SIZE)
    {
        expandTheFreeList(size);

    }
    ~MemoryPool()
    {
     MemoryPool*nextPtr=next;
        while(nextPtr)
        {
           delete [] nextPtr;
           nextPtr=next->next;
        }

    }
    void *alloc(size_t size)
    {
        if(!next)
        {
            expandTheFreeList();
        }
        MemoryPool*head=next;
        next=head->next;
        return head;

    }
    void free(void *doomed)
    {
MemoryPool*head=static_cast*>doomed;

head->next=next;
next=head;

    }
private:
    MemoryPool*next;
    enum {EXPANSION_SIZE = 32};
    void expandTheFreeList(int howMany=EXPANSION_SIZE)
    {
        size_t size=(sizeof(T)>sizeof(MemoryPool*))?sizeof(T):sizeof(MemoryPool*);
      MemoryPool*runner=static_cast*>new char [size] ;
      next=runner;
for(int i=0;inext=static_cast*>new char[size];
    runner=runner->next;
}
runner->next=NULL;

    }
};

你可能感兴趣的:(内存管理 freelist)