c++11 对象池的实现
Posted 略加思索的河马
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c++11 对象池的实现相关的知识,希望对你有一定的参考价值。
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 对象池的实现的主要内容,如果未能解决你的问题,请参考以下文章