简单的计数智能指针实现

来源:互联网 发布:武汉科瑞财富网络 编辑:程序博客网 时间:2024/05/01 15:03
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;}

0 0
原创粉丝点击