很多系统对资源的访问快捷性及可预测性有严格要求,列入包括网络连接、对象实例、线程和内存。而且还要求解决方案可扩展,能应付存在大量资源的情形。

object pool针对特定类型的对象循环利用,这些对象要么创建开销巨大,要么可创建的数量有限。而且在pool中的对象需要做到无状态。

然后转了这位博主的代码,还在研究中

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;
};
ObjectPool.cpp

相关文章:

  • 2022-12-23
  • 2022-01-07
  • 2021-06-05
  • 2022-12-23
  • 2021-11-07
  • 2021-06-12
  • 2021-06-09
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-12-29
  • 2021-07-14
  • 2022-12-23
  • 2022-12-23
  • 2021-06-22
  • 2021-08-16
相关资源
相似解决方案