1. 程式人生 > >簡單的計數智慧指標實現

簡單的計數智慧指標實現

template<class T>
class myCountPtr{
     public:
       T *p_re;
       int *count;
     public:
       explicit myCountPtr(T *p=0):p_re(p),count(new int(1)){ }
       
       myCountPtr( const myCountPtr<T>& rhs):p_re(rhs.getRe()),count(rhs.getCount())
       { 
        
         ++(*count);
       }
       T* getRe()const{return p_re;} 
        
       myCountPtr<T>& operator=(const myCountPtr<T>& rhs)
       {
           if(this!=&rhs)
            {
              depose();
              p_re=rhs.getRe();
              count=rhs.count;
              ++(*count);
            }
         return *this;
       }
       T & operator*(){return *p_re;}
       T*  operator->(){return p_re;}
       ~myCountPtr()
       {
         depose();
       }
       int *getCount(){return count;}
       void depose()
       {
         if(--(*count)==0)
          {
            delete count;
            delete p_re;
          }
        }
};

int main()
{
   myCountPtr<string> p1(new string("hello"));
 
   cout<<*p1<<" "<<*(p1.getCount())<<endl;
   myCountPtr<string> p2;
   p2=p1;
   cout<<*p2<<" "<<*(p2.getCount())<<endl;
   cout<<*p1<<" "<<*(p1.getCount())<<endl;
}