如何在boost :: object_pool中使用boost :: shared_ptr / std :: shared_ptr?

时间:2015-05-20 09:41:45

标签: boost shared-ptr pool

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

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

  3. 之后如何清理记忆?

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

1 个答案:

答案 0 :(得分:1)

是否需要成为共享指针?

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