可以参照之前的两篇博客《普通内存池的实现》、《通用内存池的实现》
单例模式的实现:
(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> single