1
template<typename T>
class Smart_Ptr {
public:
    Smart_Ptr(T* s) : source(s){ 
        cnt = new int(1);
    }
    Smart_Ptr(Smart_Ptr& p) {
        source = p.source;
        ++(*p.cnt);
        cnt = p.cnt;
    }
    ~Smart_Ptr() {
        destroy();
    }
    Smart_Ptr<T>& operator=(Smart_Ptr& p) {
        ++(*p.cnt); // must be in first line, avoid the situation " p = p" 
        destroy();
        source = p.source;
        cnt = p.cnt;
        return *this;
    }
    T* operator->() {
        return source;
    }
    T& operator*() {
        return *source;
    }
private:
    T* source;
    int* cnt;
    void destroy() {
        if (*cnt <= 1) {
            delete source;
            delete cnt;
        }
        --(*cnt);
    }    
};

shiyang6017
158 声望59 粉丝