C++对象池

//
//  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__) */

//待解决的问题: 就是内存会居高不下,如何进行回收????
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值