对象池的实现事实上是很easy的
思想也是非常easy的:
用一个队列来存放全部的对象,须要时get一个对象,从队列头取一个对象,当用完后。又一次将该对象投入到队列尾部。
#ifndef OBJ_POOL_H_
#define OBJ_POOL_H_
#include <queue>
#include <memory>
#include <stdexcept>
using std::queue;
using std::shared_ptr;
template <typename T>
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<T> getObj(){
if(freeList.empty()){
allocateChunk();
}
auto obj=freeList.front();
freeList.pop();
return obj;
}
void releaseObj(shared_ptr<T> obj){
freeList.push(obj);
}
protected:
queue<shared_ptr<T>> freeList;
int mSize;
static const int defaultSize=30;
void allocateChunk(){
for(int i=0;i<mSize;i++){
freeList.push(std::make_shared<T>());
}
}
private:
ObjPool(const ObjPool<T> &src)=delete;
ObjPool<T> &operator=(const ObjPool<T> &rhs)=delete;
};
#endif
—————————————————————————————————————————————————————————————————
//写的错误或者不好的地方请多多指导。能够在以下留言或者点击左上方邮件地址给我发邮件,指出我的错误以及不足,以便我改动,更好的分享给大家,谢谢。
转载请注明出处:http://blog.csdn.net/qq844352155
author:天下无双
Email:royalchen@royalchen.com
2015-7-18
于广州天河荷光路
——————————————————————————————————————————————————————————————————