C++实现简单的对象池
对象池的实现其实是非常简单的
思想也是很简单的:
用一个队列来存放所有的对象,需要时get一个对象,从队列头取一个对象,当用完后,重新将该对象投入到队列尾部。
#ifndef OBJ_POOL_H_
#define OBJ_POOL_H_
#include
#include
#include
using std::queue;
using std::shared_ptr;
template
class ObjPool{
public:
ObjPool(int size=defaultSize) throw(std::invalid_argument,std::bad_alloc){
if(0==size){
throw std::invalid_argument(“size can’t not small than zero”);
}
mSize=size;
allocateChunk();
}
shared_ptr
if(freeList.empty()){
allocateChunk();
}
auto obj=freeList.front();
freeList.pop();
return obj;
}
void releaseObj(shared_ptr
freeList.push(obj);
}
protected:
queue<shared_ptr
int mSize;
static const int defaultSize=30;
void allocateChunk(){
for(int i=0;i<mSize;i++){
freeList.push(std::make_shared
}
}
private:
ObjPool(const ObjPool
ObjPool
};
#endif
—————————————————————————————————————————————————————————————————
//写的错误或者不好的地方请多多指导,可以在下面留言或者点击左上方邮件地址给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。
转载请注明出处:http://blog.csdn.net/qq844352155
author:天下无双
Email:royalchen@royalchen.com
2015-7-18
于广州天河荷光路
——————————————————————————————————————————————————————————————————
- 本文作者: royalchen
- 本文链接: http://www.royalchen.com/2016/02/24/c实现简单的对象池/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!