码迷,mamicode.com
首页 > 编程语言 > 详细

C++实现的简单的内存池

时间:2014-08-22 16:30:49      阅读:285      评论:0      收藏:0      [点我收藏+]

标签:链表   内存池   

用空闲链表的方式组织一连串的分配的空间,且在此程序中仅支持内置类型。只是实现了简单的分配和回收。


#include<iostream>
#include<assert.h>
#include<stdlib.h>
using namespace std;
int const MAX=100;
struct block{
   block *next;
   block *addr;
   explicit block(int _size):next(NULL){addr=(block*)malloc(_size);}
   ~block(){delete next;delete addr;next=NULL;addr=NULL;}
};

struct list{
    block *freeList;
    block *used;
    list():freeList(NULL),used(NULL){}
    ~list(){delete freeList;delete used;}
};
class myPool{
    public:
      explicit myPool(int requester_size):size_type(requester_size){
          pool =new list;
          pool->freeList=new block(size_type);
          block *head=pool->freeList;
          for(int i=0;i<10;i++)
          {
            block *p=new block(size_type);
            head->next=p;
            head=head->next;
          }
          head = pool->freeList;		  
      }
       void *alloc()
       {
        block *alc;
        block *prev=pool->freeList;
        cout<<"start "<<pool->freeList<<endl;
        if(prev!=NULL)
        alc=prev->next;
        else return NULL;
        if(prev->next==NULL)
        {
          alc=prev;
          prev=NULL;
          return alc;
        }
        while(alc->next!=NULL)
        {
              prev=prev->next;
              alc=prev->next;
        }
        prev->next=NULL;//移出已分配的区块
        //cout<<alc<<endl;
        return alc;
       }
     void dealc(void* addr)
       {
        block *head=pool->freeList;
        while(head->next!=NULL)
        {
           head=head->next;
        }
        head->next=(block*)(addr);
        head->next->next=NULL;
       }
       ~myPool(){delete pool;}
    private:
      int size_type;
      list *pool; 
};


int main()
{
   myPool my(sizeof(int));
   int *a=(int*)my.alloc();
   *a=5;
   cout<<a<<" "<<*a<<endl;
   my.dealc(a);
   cout<<a<<" "<<*a<<endl;
   return 0;
}
bubuko.com,布布扣

C++实现的简单的内存池

标签:链表   内存池   

原文地址:http://blog.csdn.net/igiqoanw/article/details/38756461

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!