简易内存池的实现

  参考<<Effective C++>>一书中的条款10:"如果写了operator new就要同时写operator delete",写了一个简易的内存池,说白了就是事先分配一块内存空间作为内存池,每次new对象的时候,直接从这里取内存,delete的时候将内存回收到内存池中,代码很简单,废话就不说了,直接看代码。

#include "stdafx.h"
#include <iostream>

using namespace std;

//内存池
template<typename T>  
class pool
{
public:
    pool(size_t element_num)
    {
        if (element_num <= 0 )
        {
            exit(0);
        }
        headoffreelist = (T *)malloc(sizeof(T) * element_num);
        if (NULL == headoffreelist)
        {
            exit(0);
        }
        int i = 0;
        for (; i < element_num - 1; i++)  //将内存串起来
        {
            *(T** )(headoffreelist + i) = headoffreelist + i + 1;
        }
        *(T** )(headoffreelist + i) = NULL;
        pstart = headoffreelist;
    }

    ~pool(void)
    {
        free(pstart);
    }

    T *alloc(void)
    {
        cout<<"T *alloc(void)"<<endl;
        if (NULL == headoffreelist)
        {
            cout<<"Out of memory"<<endl;
            exit(0);
        }
        T *p = headoffreelist;
        headoffreelist = *(T**)headoffreelist;
        return p;
    }

    void dealloc(T* p)
    {
        cout<<"void dealloc(T* p)"<<endl;
        *(T **)p = headoffreelist;
        headoffreelist = p;
    }
private:
    void *pstart;       //记住分配的首地址,用于内存释放
    T *headoffreelist;  //未使用内存的首地址
};

//使用内存池的对象的大小不能小于一个指针的大小,否则会出错!
class airplane
{
public:
    airplane (int number = 0) : number(number){}
    static void* operator new(size_t size)
    {
        return mempool.alloc();
    }
    static void operator delete(void *p)
    {
        mempool.dealloc((airplane*)p);
    }

private:
    static pool<airplane> mempool;
    int number;
};

pool<airplane> airplane::mempool(10); //预先分配10个airplane的内存空间

int _tmain(int argc, _TCHAR* argv[])
{
    airplane *p1 = new airplane;
    airplane *p2 = new airplane;
    airplane *p3 = new airplane;
    delete p3;
    airplane *p4 = new airplane;
    delete p1;
    delete p2;
    delete p4;

    system("pause");
    return 0;
}

运行界面如下:

                                        

posted @ 2012-10-08 19:31  venow  阅读(552)  评论(0编辑  收藏  举报