一个简单的针对原数据类型的内存池模型,纯粹为了练习下c++,没做特别的考虑.
#include <new>
#include <iostream>
#include <vector>
#ifndef POOL
#define POOL 1
//针对每一种原数据类型类型(或者是有trival构造函数的自定义类型),存在一个pool
template<class Elem> class pool
{
private:
union node
{
Elem e;
node * next;
};
private:
node * head;
int initialSize;
double grads;
std::vector<node*> ptrlist; //简单以vector保存每次new后的指针,实际上我们可以不用保存,可以通过计算来得到
private:
pool (const pool & cp)
{}
pool & operator =(const pool & cp)
{
return *this;
}
public:
pool(int init=10, double pgrad=0.7):initialSize(init),grads(pgrad)//初始的池中对象的个数
{
head =static_cast<node*>(::operator new(sizeof(node) * init));
ptrlist.push_back(head);
for(int i=0;i<init-1;++i)
{
head[i].next=&head[i+1];
}
head[init-1].next= 0;
}
//分配一个单元的内存
void * alloc(size_t size)
{
if(size!=sizeof(Elem))
return ::operator new(initialSize);
void *temp = head;
if(head)
{
head= head->next;
return temp;
}
//当前池缺少空间,再次分配
try{
head=(node*)::operator new( static_cast<int>(initialSize*grads) * sizeof(node));
ptrlist.push_back(head);
}
catch(std::bad_alloc&)
{
std::cout<<"no memory can get/n";
throw;
}
int _alloc_num=static_cast<int>(initialSize*grads);
for(int i=0 ; i< _alloc_num-1; ++i)
{
head[i].next=&head[i+1];
}
head[_alloc_num-1].next= 0;
temp = head;
head = head->next;
return temp;
}
//释放一个单元的内存
void free(void * p,size_t size)
{
if(p==0)
return;
if(size!=sizeof(Elem))
return ::operator new(init);
node* n = static_cast<node *>(p);
n->next = head;
head=n;
}
~pool()
{
for(std::vector<node*>::iterator iter=ptrlist.begin(); iter!=ptrlist.end() ; ++iter)
::operator delete(*iter);
}
}
;
#endif //POOL