boost 智能指针intrusive_ptr

boost::intrusive_ptr一种“侵入式”的引用计数指针,它实际并不提供引用计数功能,而是要求被存储的对象自己实现引用计数功能,并提供intrusive_ptr_add_ref和intrusive_ptr_release函数接口供boost::intrusive_ptr调用

 intrusive_ptr是一个侵入式的引用计数型指针,它可以用于以下两种情形:
 【1】对内存占用的要求非常严格,要求必须与原始指针一样;
 【2】现存代码已经有了引用计数机制管理的对象。

。Boost库不推荐使用intrusive_ptr,因为shared_ptr已经非常强大且灵活,工作的足够好,可以满足绝大部分(99.99%)的需要。

头文件: "boost/intrusive_ptr.hpp"

intrusive_ptr 是shared_ptr的插入式版本。有时我们必须使用插入式的引用计数智能指针。典型的情况是对于那些已经写好了内部引用计数器的代码,而我们又没有时间去重写它(或者已经不能获得那些代码了)。另一种情况是要求智能指针的大小必须与裸指针大小严格相等,或者shared_ptr的引用计数器分配严重影响了程序的性能(我可以肯定这是非常罕见的情况!)。从功能的观点来看,唯一需要插入式智能指针的情况是,被指类的某个成员函数需要返回this,以便它可以用于另一个智能指针(事实上,也有办法使用非插入式智能指针来解决这个问题,正如我们在本章前面看到的)。intrusive_ptr 不同于其它智能指针,因为它要求你来提供它所要的引用计数器。

当 intrusive_ptr 递增或递减一个非空指针上的引用计数时,它是通过分别调用函数 intrusive_ptr_add_ref 和 intrusive_ptr_release来完成的。这两个函数负责确保引用计数的正确性,并且负责在引用计数降为零时删除指针。因此,你必须为你的类重载这两个函数,正如我们后面将看到的。

以下是intrusive_ptr的部分摘要,只列出了最重要的函数。

namespace boost {

  template<class T> class intrusive_ptr {
  public:
    intrusive_ptr(T* p,bool add_ref=true);

    intrusive_ptr(const intrusive_ptr& r);

    ~intrusive_ptr();

    T& operator*() const;
    T* operator->() const;
    T* get() const; 

    operator unspecified-bool-type() const; 
  };

  template <class T> T* get_pointer(const intrusive_ptr<T>& p); 

  template <class T,class U> intrusive_ptr<T>
    static_pointer_cast(const intrusive_ptr<U>& r); 
}



http://blog.csdn.net/harbinzju/article/details/6754646


原文地址:https://www.cnblogs.com/youxin/p/4326166.html