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; };
时间: 2024-10-05 06:18:13