C++自定义高效对象池

54 阅读1分钟
class ObjdectPool
{
public:
    using DelType = std::function<void(T *)>;

    void add(std::unique_ptr<T> t)
    {
        m_pool.push_back(std::move(t));
    }

    std::shared_ptr<T> get()
    {
        std::lock_guard<std::mutex> lock_g(this->mtx_);
        if (m_pool.empty())
        {
            throw std::logic_error("no object");
        }
        
        // 创建一个带有自定义删除器的 unique_ptr
        std::unique_ptr<T, DelType> s_ptr(m_pool.back().release(), [=](T *t) {
            std::lock_guard<std::mutex> lock_d(this->mtx_);
            m_pool.push_back(std::unique_ptr<T>(t));  // 将释放的对象放回池中
        });
        
        std::shared_ptr<T> ptr = std::move(s_ptr);  // 转换为 shared_ptr
        m_pool.pop_back();  // 从池中移除 unique_ptr
        return ptr;  // 返回 shared_ptr
    }

    bool empty() const {
        return m_pool.empty();
    }

    int size() const {
        return m_pool.size();
    }

private:
    std::vector<std::unique_ptr<T>> m_pool;  // 存储对象的 unique_ptr 向量
    std::mutex mtx_;  // 用于线程安全的互斥量
};