一个简单地内存池

#include<iostream>
using namespace std;

class MemPool{
private:
	typedef struct Node{
		void* data;
		Node* next;
	}Node;
	Node* nodesHead_;
	Node* firstFree_;
	Node* usedNodes_;
	void* data;
	int capacity_;
	int size_;
	int unitSize_;
public:
	MemPool(int unitSize,int maxSize):nodesHead_(new Node[maxSize]),firstFree_(nodesHead_),usedNodes_(NULL),
		capacity_(maxSize),size_(0),unitSize_(unitSize){
		data=operator new(unitSize_*capacity_);
		for(int i=0;i<capacity_;++i)
			nodesHead_[i].data=(char*)data+i*unitSize;
		for(int i=0;i<capacity_-1;++i)
			nodesHead_[i].next=nodesHead_+i+1;
		nodesHead_[capacity_-1].next=NULL;
	}
	~MemPool(){
		delete[] data;
		delete[] nodesHead_;
	}
	void* Alloc(){
		if(size_==capacity_)return NULL;
		Node* tmp=firstFree_;
		firstFree_=firstFree_->next;
		++size_;
		tmp->next=usedNodes_;
		usedNodes_=tmp;
		return tmp->data;
	}
	void Free(void* tmp){
		if(usedNodes_==NULL)return;
		Node* p=usedNodes_;
		usedNodes_=usedNodes_->next;
		p->data=tmp;
		p->next=firstFree_;
		firstFree_=p;
		--size_;
	}
};
int cnt=1;
class Test{
public:
	int data;
	char c;
	Test(int d,char s):data(d),c(s){
		cout<<"cnt="<<cnt++<<endl;
	}
};


int main(){
	
	MemPool pool(sizeof(Test),10);
	for(int i=1;i<=20;++i){
		Test* t=(Test*)pool.Alloc();
		if(t!=NULL){
			new(t) Test(10,'a');
			cout<<t->data<<" "<<t->c<<endl;
			t->~Test();
			pool.Free((void*)t);
		}		
	}
	
	return 0;
}

元素之间用量表窜起来,包含没被使用的节点和已使用的节点。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值