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


在C++中,智能指针是存储一些动态分配对象或者资源的类,主要用于控制资源或者动态对象的使用生存期,设计的目的如下:

  1. 保证能够正确的分配和销毁动态对象或者资源,以防止内存泄露等问题。
  2. 跟踪对象或者资源的使用情况。

智能指针的实现一般都是使用引用计数,将一个计数器与使用的指针相关联起来,此时引用计数器跟踪该所属类有外部多少共享。因此在实现的时候,就有两个根本的部分

  1. 计数表示。用于实现对动态对象或者资源使用的计数。
  2. 指针表示。用于将动态对象或者资源的指针使用间接表现。

根据智能指针主要是上面两大部分,智能指针可以称为“智能计数指针”,智能主要是计数的意思,当然计数的用途就因应用而不同了,或者只是为了跟踪,或者是为了资源管理,或者是为了防止多次释放等等。

一,智能指针实现

下面的模板类,用于实现对指针的封装,其实现的功能如下:

  1. 指针构造。根据需要被封装的动态对象或者资源的指针,构造智能指针,一般在构造时,会将资源的计数加1;
  2. 指针运算符重载。下面重载了*,=,->等运算符。
  3. 指针数据。一个指向模板类型的指针,T* ptr_
  1. template <class T> 
  2. class scoped_refptr { 
  3.  public
  4.   scoped_refptr() : ptr_(NULL) { 
  5.   } 
  6.  
  7.   scoped_refptr(T* p) : ptr_(p) { 
  8.     if (ptr_) 
  9.       ptr_->AddRef(); 
  10.   } 
  11.  
  12.   scoped_refptr(const scoped_refptr<T>& r) : ptr_(r.ptr_) { 
  13.     if (ptr_) 
  14.       ptr_->AddRef(); 
  15.   } 
  16.  
  17.   template <typename U> 
  18.   scoped_refptr(const scoped_refptr<U>& r) : ptr_(r.get()) { 
  19.     if (ptr_) 
  20.       ptr_->AddRef(); 
  21.   } 
  22.  
  23.   ~scoped_refptr() { 
  24.     if (ptr_) 
  25.       ptr_->Release(); 
  26.   } 
  27.  
  28.   T* get() const { return ptr_; } 
  29.   operator T*() const { return ptr_; } 
  30.   T* operator->() const { return ptr_; } 
  31.  
  32.   T* release() { 
  33.     T* retVal = ptr_; 
  34.     ptr_ = NULL; 
  35.     return retVal; 
  36.   } 
  37.  
  38.   scoped_refptr<T>& operator=(T* p) { 
  39.     // AddRef first so that self assignment should work  
  40.     if (p) 
  41.       p->AddRef(); 
  42.     if (ptr_ ) 
  43.       ptr_ ->Release(); 
  44.     ptr_ = p; 
  45.     return *this
  46.   } 
  47.  
  48.   scoped_refptr<T>& operator=(const scoped_refptr<T>& r) { 
  49.     return *this = r.ptr_; 
  50.   } 
  51.  
  52.   template <typename U> 
  53.   scoped_refptr<T>& operator=(const scoped_refptr<U>& r) { 
  54.     return *this = r.get(); 
  55.   } 
  56.  
  57.   void swap(T** pp) { 
  58.     T* p = ptr_; 
  59.     ptr_ = *pp; 
  60.     *pp = p; 
  61.   } 
  62.  
  63.   void swap(scoped_refptr<T>& r) { 
  64.     swap(&r.ptr_); 
  65.   } 
  66.  
  67.  protected
  68.   T* ptr_; 
  69. }; 

有了这个类之后,我们可以定义一个指针,如针对class window的智能指针

scoped_refptr<window> win; 

此时,上面的模板就会包含一个window *ptr_的指针,从上面可以看出,为了能够正常工作,这类型的指针都必须要实现AddRef和Release方法,这应该不会是要求在class window中实现的吧?那也不太不符合封装的正常逻辑了。答案是:当然不会在class window中实现,这两个方法主要是针对计数的方法,专门针对class window封装一个计数器类,下面的计数器封装。

  • 1
  • 2
  • 下一页

相关内容