代码示例:
#include<iostream> using namespace std; const int MEM_POOL_SIZE = 5; template<typename T> class MEM_POOL { public: void* alloc(size_t size) { if (pool == NULL) { int allocsize = (size + 4) * MEM_POOL_SIZE; pool = (Node*)new char[allocsize]; Node* pCur = pool; for (pCur; pCur < pool + MEM_POOL_SIZE - 1; ++pCur) { pCur->pnext = pCur + 1; } pCur->pnext = NULL; } Node* rt = pool; pool = pool->pnext; return rt; } void del(void* ptr) { if (ptr == NULL) return; Node* pCur = (Node*)ptr; pCur->pnext = pool; pool = pCur; } private: class Node { public: Node() :pnext(NULL){} public: T mdata; Node* pnext; }; static Node* pool; }; //类外初始化静态成员变量 template<typename T> typename MEM_POOL<T>::Node* MEM_POOL<T>::pool = NULL; class Stu { public: Stu(int id, string name) : mid(id), mname(name) { cout << "Stu::Stu(int,string)" << endl; } void* operator new(size_t size) { return pool->alloc(size); } void operator delete(void* ptr) { pool->del(ptr); } private: int mid; string mname; static MEM_POOL<Stu>* pool; }; //类外初始化静态成员对象 MEM_POOL<Stu>* Stu::pool = new MEM_POOL<Stu>(); int main() { Stu* s1 = new Stu(1, "student1"); Stu* s2 = new Stu(2, "student2"); Stu* s3 = new Stu(3, "student3"); Stu* s4 = new Stu(4, "student4"); Stu* s5 = new Stu(5, "student5"); Stu* s6 = new Stu(6, "student6"); return 0; }