2

I want to implement an object pool, so I need to manage the memory of the object myself. So I thought of customizing the deleter of shared_ptr to realize object recycling. Below is an example ref to link

    template <typename T>
    class object_pool
    {
        std::shared_ptr<tbb::concurrent_bounded_queue<std::shared_ptr<T>>> pool_;
    public:
        object_pool() 
        : pool_(new tbb::concurrent_bounded_queue<std::shared_ptr<T>>()){}

        // Create overloads with different amount of templated parameters.
        std::shared_ptr<T> create() 
        {         
              std::shared_ptr<T> obj;
              if(!pool_->try_pop(obj))
                  obj = std::make_shared<T>();

              // Automatically collects obj.
              return std::shared_ptr<T>(obj.get(), [=](T*){pool_->push(obj);}); 
        }
    };

question

Since the std::shared_ptr's deleter does not release the memory, So how do I release the memory in the "~object_pool" function?

daohu527
  • 452
  • 4
  • 15
  • The shared pointers in pool probably just want to be normal shared pointers with standard deleters. You'd then transfer those objects to new shared pointers with your custom deleters in `create` – Alan Birtles Sep 03 '21 at 07:35

1 Answers1

1

The memory is owned by std::shared_ptr<T> obj

The returned std::shared_ptr<T>(obj.get() will not indeed explicitly delete the object, but the deleter lambda captures std::shared_ptr<T> obj by value, so the deleter of the returned pointer will own the object, until it is tranfered to pool_.

So the memory is either owned by std::shared_ptr<T> obj; from create() or by shared_ptr<T> in pool_. It is then freed when pool_ is cleared.


Use of shared_ptr is suboptimal here. Looks like the example was created before C++11 move-semantic was adopted. This can be rewritten so that pool_ and returned pointer deleter contained unique_ptr.

Alex Guteniev
  • 12,039
  • 2
  • 34
  • 79