设为首页 加入收藏

TOP

3.4.1 类摘要
2013-10-07 13:13:49 来源: 作者: 【 】 浏览:54
Tags:3.4.1 摘要

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复杂许多,它的类摘要如下:

  1. template<class T> class shared_ptr  
  2. {  
  3. public:  
  4.       typedef T element_type;  
  5.  
  6.       shared_ptr();  
  7.       template<class Y> explicit shared_ptr(Y * p);  
  8.       template<class Y, class D> shared_ptr(Y * p, D d);  
  9.       ~shared_ptr();  
  10.  
  11.       shared_ptr(shared_ptr const & r);  
  12.       template<class Y> explicit shared_ptr(std::auto_ptr<Y> & r);  
  13.  
  14.       shared_ptr & operator=(shared_ptr const & r);  
  15.       template<class Y> shared_ptr & operator=(shared_ptr<Y> const & r);  
  16.       template<class Y> shared_ptr & operator=(std::auto_ptr<Y> & r);  
  17.  
  18.       void reset();  
  19.       template<class Y> void reset(Y * p);  
  20.       template<class Y, class D> void reset(Y * p, D d);  
  21.  
  22.       T & operator*() const;  
  23.       T * operator->() const;  
  24.       T * get() const;  
  25.  
  26.       bool unique() const;  
  27.       long use_count() const;  
  28.  
  29.       operator unspecified-bool-type() const;  
  30.       void swap(shared_ptr & b);  
  31. }; 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇3.3.3 使用建议 下一篇3.3.1 类摘要

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: