码迷,mamicode.com
首页 > 编程语言 > 详细

c++11 对象池的实现

时间:2016-03-12 01:36:35      阅读:755      评论:0      收藏:0      [点我收藏+]

标签:

    const int MaxObjectNum = 10;

    template <typename T>
    class ObjectPool
    {
        template <typename... Args>
        using Constructor = std::function<std::shared_ptr<T>(Args...)>;
    public:
        ObjectPool(void)
            : m_bNeedClear(false)
        {
        }

        virtual ~ObjectPool(void)
        {
            m_bNeedClear = true;
        }
        
        template <typename... Args>
        void Init(size_t num, Args&&... args)
        {
            if (num <= 0 || num > MaxObjectNum)
            {
                throw std::logic_error("object num out of range.");
            }

            auto constructName = typeid(Constructor<Args...>).name();

            for (size_t i = 0; i < num; i++)
            {
                m_object_map.emplace(constructName,
                    std::shared_ptr<T>(new T(std::forward<Args>(args)...), [constructName, this]
                    (T* t)
                {
                    if (m_bNeedClear)
                    {
                        delete t;
                    }
                    else
                    {
                        m_object_map.emplace(constructName, std::shared_ptr<T>(t));
                    }
                }));
            }
        }

        template <typename... Args>
        std::shared_ptr<T> Get()
        {
            string constructName = typeid(Constructor<Args...>).name();

            auto range = m_object_map.equal_range(constructName);

            for (auto it = range.first; it != range.second; ++it)
            {
                auto ptr = it->second;
                m_object_map.erase(it);
                return ptr;
            }

            return nullptr;
        }


    private:
        std::multimap<std::string, std::shared_ptr<T> > m_object_map;
        bool m_bNeedClear;
        
    };

 

c++11 对象池的实现

标签:

原文地址:http://www.cnblogs.com/kaishan1990/p/5267716.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!