shared_ptr stl

#include<bits/stdc++.h>
using namespace std;


template <typename T> 
class Smartptr{
public:
   explicit Smartptr(T* =(T*)0) ;
   Smartptr<T>& operator=(Smartptr<T>&);
   Smartptr(Smartptr<T>&);
   ~Smartptr();
   T* operator->(); 
   T&  operator*();
private:
   T* ptr;
   static map<T*,int> cou; 
};

template<typename T>
map<T*,int> Smartptr<T> :: cou;


template<typename T>
Smartptr<T>::Smartptr(T* x){
    ptr = x;
    cou[x]++;
}

template<typename T>
Smartptr<T>& Smartptr<T>::operator=(Smartptr<T>& x){
     if(x.ptr == ptr)return *this;
     cou[ptr]--;
     if(cou[x.ptr]<=0){
         delete ptr;
         ptr = 0;
     }
     ptr = x.ptr;
     cou[ptr]++;
     return *this;
}

template<typename T>
Smartptr<T>::~Smartptr(){
     if(*this.ptr){
        cou[ptr]--;
        delete ptr;
     }
}
template<typename T>
Smartptr<T>::Smartptr(Smartptr<T>& x){
     ptr = x.ptr;
     cou[ptr]++;
}

int main() {
    
    return 0;
}

 

posted @ 2020-04-24 11:12  Xzavieru  阅读(106)  评论(0编辑  收藏  举报