C++实现简单的对象池
2015-07-18 16:12
477 查看
对象池的实现其实是非常简单的
思想也是很简单的:
用一个队列来存放所有的对象,需要时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
于广州天河荷光路
——————————————————————————————————————————————————————————————————
思想也是很简单的:
用一个队列来存放所有的对象,需要时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
于广州天河荷光路
——————————————————————————————————————————————————————————————————
相关文章推荐
- c语言中malloc、realloc与calloc 的区别以及联系
- C++中new与delete、malloc与free应用分析
- new和malloc的区别深入解析
- new、delelte和malloc、free的关系
- 初识英特尔线程构建模块之内存管理tbb_malloc
- 浅谈C中的malloc和free
- 一级指针和二级指针做形参分配动态地址空间
- 用brk实现sbrk,关于brk的返回值
- C语言堆内存堆申请与文件读入的性能分析
- C中动态分配内存
- malloc要不要强制转换返回值
- C/C++中野指针的问题
- 数据结构 第三季(part 3)
- C语言中malloc 动态申请多维数组
- 产生随机组丢到txt中
- 关于STDLIB.H头文件中的函数应用
- new/delete和malloc/free的区别
- 环形buffer的实现
- malloc函数详解
- 关于malloc()函数以及free()报heap buffer错误的问题