3.4 shared_ptr
shared_ptr是一个最像指针的"智能指针",是boost.smart_ptr库中最有价值、最重要的组成部分,也是最有用的,Boost库的许多组件--甚至还包括其他一些领域的智能指针都使用了shared_ptr。抱歉,我实在想不出什么更恰当的词汇来形容它在软件开发中的重要性。再强调一遍,shared_ptr非常有价值、非常重要、非常有用。
shared_ptr与scoped_ptr一样包装了new操作符在堆上分配的动态对象,但它实现的是引用计数型的智能指针 ,可以被自由地拷贝和赋值,在任意的地方共享它,当没有代码使用(引用计数为0)它时才删除被包装的动态分配的对象。shared_ptr也可以安全地放到标准容器中,并弥补了auto_ptr因为转移语义而不能把指针作为STL容器元素的缺陷。
在C++(www.cppentry.com)历史上曾经出现过无数的引用计数型智能指针实现,但没有一个比得上boost::shared_ptr,在过去、现在和将来,它都是最好的。
3.4.1 类摘要
shared_ptr要比同为智能指针的scoped_ptr复杂许多,它的类摘要如下:
- template<class T> class shared_ptr
- {
- public:
- typedef T element_type;
-
- shared_ptr();
- template<class Y> explicit shared_ptr(Y * p);
- template<class Y, class D> shared_ptr(Y * p, D d);
- ~shared_ptr();
-
- shared_ptr(shared_ptr const & r);
- template<class Y> explicit shared_ptr(std::auto_ptr<Y> & r);
-
- shared_ptr & operator=(shared_ptr const & r);
- template<class Y> shared_ptr & operator=(shared_ptr<Y> const & r);
- template<class Y> shared_ptr & operator=(std::auto_ptr<Y> & r);
-
- void reset();
- template<class Y> void reset(Y * p);
- template<class Y, class D> void reset(Y * p, D d);
-
- T & operator*() const;
- T * operator->() const;
- T * get() const;
-
- bool unique() const;
- long use_count() const;
-
- operator unspecified-bool-type() const;
- void swap(shared_ptr & b);
- };