#pragma once #include #include #include #include template class ObjectPool { public: using ptr_type = std::unique_ptr>; ObjectPool(std::function()> createObject) : createObject(createObject) {} virtual ~ObjectPool() {} ptr_type acquire() { std::lock_guard lock(poolMutex); if (pool.empty()) { pool.push(createObject()); } ptr_type tmp(pool.top().release(), [this](T* p) { std::lock_guard lock(poolMutex); this->pool.push(std::unique_ptr(p)); }); pool.pop(); return std::move(tmp); } bool empty() const { std::lock_guard lock(poolMutex); return pool.empty(); } size_t size() const { std::lock_guard lock(poolMutex); return pool.size(); } private: std::function createObject; std::stack> pool; mutable std::mutex poolMutex; };