• 简单C++对象池实现


    / *ObjectPool.h */
    
    #include <iostream>
    #include <queue>
    #include <vector>
    
    template <typename T>
    class ObjectPool
    {
    public:
    	ObjectPool(size_t chunk_size = kdefault_size);
    	~ObjectPool();
    
    	T& acquire_object();
    	void release_object(T& obj);
    
    protected:
    	void allocate_chunk();
    	static void array_delete_object(T* obj);
    
    private:
    	std::queue<T*> free_list_;
    	std::vector<T*> all_objects_;
    	int chunk_size_;							//对象池中预分配对象个数
    	static const size_t kdefault_size = 100;	//默认对象池大小
    
    	ObjectPool(const ObjectPool<T>& src);
    	ObjectPool<T>& operator=(const ObjectPool<T>& rhs);
    };
    

      

    /* ObjectPool.cpp */
    
    #include "ObjectPool.h"
    #include <algorithm>
    
    template <typename T>
    const size_t ObjectPool<T>::kdefault_size;
    
    template <typename T>
    ObjectPool<T>::ObjectPool(size_t chunk_size /* = kdefault_size */) : chunk_size_ (chunk_size)
    {
    	if (chunk_size_ <= 0)
    	{
    		std::cout << "Object size invalid" << std::endl;
    	}
    	else
    	{
    		allocate_chunk();
    	}
    }
    
    template <typename T>
    void ObjectPool<T>::array_delete_object(T* obj)
    {
    	delete obj;
    }
    
    template <typename T>
    ObjectPool<T>::~ObjectPool()
    {
    	std::for_each(all_objects_.begin(), all_objects_.end(), ObjectPool<T>::array_delete_object);
    }
    
    template <typename T>
    void ObjectPool<T>::allocate_chunk()
    {
    	T* new_objects = new T(chunk_size_);
    	for (int i = 0; i < chunk_size_; ++i)
    	{
    		all_objects_.push_back(&new_objects[i]);
    		free_list_.push(&new_objects[i]);
    	}
    }
    
    template <typename T>
    T& ObjectPool<T>::acquire_object()
    {
    	if (free_list_.empty())
    	{
    		allocate_chunk();
    	}
    	T *obj = free_list_.front();
    	free_list_.pop();
    	return (*obj);
    }
    
    template <typename T>
    void ObjectPool<T>::release_object(T& obj)
    {
    	free_list_.push(&obj);
    }
    

      

    来自《Professional C++》

  • 相关阅读:
    linux包之coreutils之du和df命令
    java实现第六届蓝桥杯加法变乘法
    java实现第六届蓝桥杯奇妙的数字
    java实现第六届蓝桥杯奇妙的数字
    java实现第六届蓝桥杯打印大X
    java实现第六届蓝桥杯移动距离
    java实现第六届蓝桥杯移动距离
    java实现第六届蓝桥杯循环节长度
    java实现第六届蓝桥杯奇妙的数字
    java实现第六届蓝桥杯格子中输出
  • 原文地址:https://www.cnblogs.com/good90/p/2963366.html
Copyright © 2020-2023  润新知