【问题标题】:How to use boost::shared_ptr/std::shared_ptr with boost::object_pool?如何将 boost::shared_ptr/std::shared_ptr 与 boost::object_pool 一起使用?
【发布时间】:2015-05-20 09:41:44
【问题描述】:
  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)
}

【问题讨论】:

    标签: boost shared-ptr pool


    【解决方案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';
    }
    

    【讨论】:

      猜你喜欢
      • 2011-09-27
      • 1970-01-01
      • 2015-05-04
      • 2011-02-19
      • 2018-02-19
      • 2013-06-12
      • 2013-04-16
      • 1970-01-01
      • 2011-12-28
      相关资源
      最近更新 更多