C++ object-pool that provides items as smart-pointers that are returned to pool upon deletion

前端 未结 4 1858
渐次进展
渐次进展 2020-12-12 18:48

I\'m having fun with c++-ideas, and got a little stuck with this problem.

I would like a LIFO class that manages a pool of resources. When a resource is

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-12 19:03

    Here's a custom deleter that checks if the pool is still alive.

    template
    class return_to_pool
    {
      std::weak_ptr> pool
    
    public:
      return_to_pool(const shared_ptr>& sp) : pool(sp) { }
    
      void operator()(T* p) const
      {
        if (auto sp = pool.lock())
        {
          try {
            sp->add(std::unique_ptr(p));
            return;
          } catch (const std::bad_alloc&) {
          }
        }
        std::default_delete{}(p);
      }
    };
    
    template 
    class SharedPool : std::enable_shared_from_this>
    {
    public:
      using ptr_type = std::unique_ptr>;
      ...
      ptr_type acquire()
      {
        if (pool_.empty())
          throw std::logic_error("pool closed");
        ptr_type tmp{pool_.top().release(), this->shared_from_this()};
        pool_.pop();
        return tmp;
      }
      ...
    };
    
    // SharedPool must be owned by a shared_ptr for enable_shared_from_this to work
    auto pool = std::make_shared>();
    

提交回复
热议问题