std::shared_ptr with custom deleter?

Viewed 433

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?

1 Answers

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.

Related