zoukankan      html  css  js  c++  java
  • 简单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++》

  • 相关阅读:
    CentOS7使用firewalld打开关闭防火墙与端口
    SELinux: Could not downgrade policy file
    CentOS 安装 semanage 命令
    漏洞: RHSA2017:3075: wget security update
    CentOS7增加或修改SSH端口号
    gnl's not lao 道德经 英文版
    当代 IT 大牛排行榜
    当代 IT 大牛排行榜
    2008 年个人回忆与总结
    Patch2 for NetBeans IDE 6.5 Now Available
  • 原文地址:https://www.cnblogs.com/good90/p/2963366.html
Copyright © 2011-2022 走看看