参考<
#include "stdafx.h" #includeusing 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; }
运行界面如下: