//
// SimpleObjectPool.h
// ObjectPool
//
// Created by user on 13-5-20.
// Copyright (c) 2013年 user. All rights reserved.
//
#ifndef __ObjectPool__SimpleObjectPool__
#define __ObjectPool__SimpleObjectPool__
#include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
//默认对象池大小
static const int kdefault_size = 100;
//每次增长10个
static const int kIncrease_size = 10;
template <typename T>
class ObjectPool
{
private:
//空闲的
queue<T*> free_list_;
// 所有的对象
vector<T*> all_objects_;
//对象池中预分配对象个数
int chunk_size_;
// 拷贝构造函数
ObjectPool(const ObjectPool<T>& src);
// 赋值
ObjectPool<T>& operator=(const ObjectPool<T>& rhs);
public:
ObjectPool(int chunk_size = kdefault_size){
chunk_size_ = chunk_size;
if (chunk_size_ <= 0)
{
cout << "Object size invalid" << endl;
}
else
{
allocate_chunk(chunk_size_);
}
};
~ObjectPool(){
std::for_each(all_objects_.begin(), all_objects_.end(), ObjectPool<T>::array_delete_object);
};
T* acquire_object(){
if (free_list_.empty())
{
CCLog("开始新分配对象");
allocate_chunk(kIncrease_size);
}
T *obj = free_list_.front();
free_list_.pop();
return obj;
};
void release_object(T* obj){
free_list_.push(obj);
};
int getFreeObjectSize()
{
return free_list_.size();
}
protected:
void allocate_chunk(int allocateSize){
T* new_objects = new T[allocateSize];
for (int i = 0; i < allocateSize; ++i)
{
all_objects_.push_back(&new_objects[i]);
free_list_.push(&new_objects[i]);
}
};
static void array_delete_object(T* obj){
delete obj;
};
};
#endif /* defined(__ObjectPool__SimpleObjectPool__) */
//待解决的问题: 就是内存会居高不下,如何进行回收????