C++ : 智能指针

template
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& 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);
    }    
};

你可能感兴趣的:(c++)