菜鸟笔记
提升您的技术认知

简易内存池的实现-ag真人游戏

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

#include "stdafx.h"
#include 
using namespace std;
//内存池
template  
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 mempool;
    int number;
};
pool 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;
}

运行界面如下:

                                        

网站地图