用空闲链表的方式组织一连串的分配的空间,且在此程序中仅支持内置类型。只是实现了简单的分配和回收。
#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; }
原文地址:http://blog.csdn.net/igiqoanw/article/details/38756461