如何使用 boost::shared_ptr/std::shared_ptr 和 boost::object_pool?

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

  1. 我是否应该使用带有 boost::object_pool 的共享指针来防止内存泄漏(以防 malloc-destroy 块内发生异常)?

  2. 如果是,正确的初始化方法是什么shared_ptr?

  3. 之后如何清理内存?

#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)
}

是否需要共享指针?

unique_ptr 有利于将删除器编码为类型:

#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';
}