手机版
你好,游客 登录 注册
背景:
阅读新闻

一个C++中智能指针的设计

[日期:2012-11-27] 来源:Linux社区  作者:zmxiangde_88 [字体:大 中 小]

二,计数器的封装

这个类很简单,有三个地方需要注意

  1. 类从模板类型继承,就是从T继承。上面的class window的话,就是RefCountedObject是window的派生类。
  2. 封装计数器ref_count_。需要注意的是,对计数器的加减操作应该尽可能的保持原子性。
  3. 计数器类提供多个构造函数,都是对传入的类型T的多种构造支持。
  4. template <class T> 
  5. class RefCountedObject : public T { 
  6.  public: 
  7.   RefCountedObject() : ref_count_(0) { 
  8.   } 
  9.  
  10.   template<typename P> 
  11.   explicit RefCountedObject(P p) : T(p), ref_count_(0) { 
  12.   } 
  13.  
  14.   template<typename P1, typename P2> 
  15.   RefCountedObject(P1 p1, P2 p2) : T(p1, p2), ref_count_(0) { 
  16.   } 
  17.  
  18.   template<typename P1, typename P2, typename P3> 
  19.   RefCountedObject(P1 p1, P2 p2, P3 p3) : T(p1, p2, p3), ref_count_(0) { 
  20.   } 
  21.  
  22.   template<typename P1, typename P2, typename P3, typename P4> 
  23.   RefCountedObject(P1 p1, P2 p2, P3 p3, P4 p4) 
  24.       : T(p1, p2, p3, p4), ref_count_(0) { 
  25.   } 
  26.  
  27.   template<typename P1, typename P2, typename P3, typename P4, typename P5> 
  28.   RefCountedObject(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) 
  29.       : T(p1, p2, p3, p4, p5), ref_count_(0) { 
  30.   } 
  31.  
  32.   virtual ~RefCountedObject() { 
  33.   } 
  34.  
  35.   virtual int AddRef() { 
  36.     return Increment(&ref_count_); 
  37.   } 
  38.  
  39.   virtual int Release() { 
  40.     int count = Decrement(&ref_count_); 
  41.     if (!count) { 
  42.       delete this; 
  43.     } 
  44.     return count; 
  45.   } 
  46.  
  47.  protected: 
  48.   int ref_count_; 
  49. }; 

三,实例

scoped_refptr<Window> win(new RefCountedObject<Window>(&client, &wnd)); 

上面的实例定义了一个智能指针win,式中client和wnd为其它参数,与定义无关。

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款