Search code examples
boostshared-ptrpool

How to use boost::shared_ptr/std::shared_ptr with boost::object_pool?


  1. Should I ever prevent memory leaks using shared pointers with boost::object_pool (in case of an exception inside malloc-destroy block)?

  2. If yes, what is the correct way to initialize shared_ptr?

  3. How to clean up memory afterwards?

#include <boost/pool/object_pool.hpp>
#include <boost/shared_ptr.hpp>

int main() {
    boost::object_pool<int> pool;
    // Which is the correct way of initializing the shared pointer:

    // 1)
    int *i = pool.malloc();
    boost::shared_ptr<int> sh(i);
    int *j = pool.construct(2);
    boost::shared_ptr<int> sh2(j);

    // or 2)
    boost::shared_ptr<int> sh(pool.malloc());

    // Now, how should i clean up the memory?
    // without shared_ptr I'd call here pool.destroy(i) and pool.destroy(j)
}

Solution

  • Does it need to be a shared pointer?

    unique_ptr has the benefit to encode the deleter into the type:

    #include <boost/pool/object_pool.hpp>
    
    template <typename T, typename Pool = boost::object_pool<T> >
    struct pool_deleter {
        pool_deleter(Pool& pool) : _pool(pool) {}
        void operator()(T*p) const { _pool.destroy(p); }
      private:
        Pool& _pool;
    };
    
    #include <memory>
    
    template <typename T> using pool_ptr 
        = std::unique_ptr<T, pool_deleter<T, boost::object_pool<T> > >;
    
    int main() {
        boost::object_pool<int> pool;
        pool_ptr<int> i(pool.construct(42), pool);
    
        std::cout << *i << '\n';
    }