可以参照之前的两篇博客《普通内存池的实现》、《通用内存池的实现》
单例模式的实现:
(1)构造函数写在私有成员里面
(2)有一个静态的成员函数用来生成一个唯一的对象
代码实现:
#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; } static MEM_POOL<T>* getInstance()//创建唯一的对象 { static MEM_POOL<T> singleobject; return &singleobject; } private: MEM_POOL(){} MEM_POOL(const MEM_POOL<T>&); class Node { public: Node() :pnext(NULL){} public: T mdata; Node* pnext; }; static Node* pool; static MEM_POOL<T>* single; }; template<typename T> MEM_POOL<T>* MEM_POOL<T>::single = MEM_POOL<T>::getInstance(); 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 = MEM_POOL<Stu>::getInstance(); int main() { Stu* student1 = new Stu(1, "student1"); Stu* student2 = new Stu(2, "student2"); Stu* student3 = new Stu(3, "student3"); Stu* student4 = new Stu(4, "student4"); Stu* student5 = new Stu(5, "student5"); Stu* student6 = new Stu(6, "student6"); MEM_POOL<Stu> *pool1 = MEM_POOL<Stu>::getInstance(); MEM_POOL<Stu> *pool2 = MEM_POOL<Stu>::getInstance(); MEM_POOL<Stu> *pool3 = MEM_POOL<Stu>::getInstance(); MEM_POOL<Stu> *pool4 = MEM_POOL<Stu>::getInstance(); return 0; }