简单的内存池模型

一个简单的针对原数据类型的内存池模型,纯粹为了练习下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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值