智能指针实现

下面是一个智能指针的实现,很好,可以多多采用。


#ifndef SMART_PTR_H
#define SMART_PTR_H

//智能指针,可以加入set或map,利用其排序参数进行排序
//set或map调用clear或erase会调用SmartPtr析构函数,不再被引用的数据指针会被delete

template <class T>
class SmartPtr
 {
     private:
   T* ptr;        // pointer to the value  指针
   long* count;   // shared number of owners  计数
     public:
   //initialize pointer with existing pointer
   //-requires that the pointer p is a return value of new
  
   //构造函数  用explicit修饰,不允许隐形转换
   explicit SmartPtr (T* p=0)
    : ptr(p), count(new long(1))
   {
   }

   //copy pointer (one more owner)  复制构造函数
   SmartPtr (const SmartPtr<T>& p) throw()
    : ptr(p.ptr), count(p.count)
   {
    ++*count;
   }

   //destructor (delete value if this was the last owner)析构函数
   ~SmartPtr () throw()
   {
    dispose();
   }

   //assignment (unshare old and share new value)  重载assignment 运算符
   SmartPtr<T>& operator= (const SmartPtr<T>& p) throw()
   {
    if (this != &p)
    {
     dispose();
     ptr = p.ptr;
     count = p.count;
     ++*count;
    }
    return *this;
   }

   //access the value to which the pointer refers 重载* 运算符
   T& operator*() const throw()
   {
    return *get();
   }

   T* operator->() const throw()
   {
    return get();
   }

   T* get() const throw()
   {
    return  ptr;
   }
   

     private: 
   //销毁
   void dispose()
   {
    if (--*count == 0) {
     delete count;
     delete ptr;
    }
   }
};


#endif

原文地址:https://www.cnblogs.com/skyofbitbit/p/2677407.html