SmartPtr

// smart pointer implements


#include 
#include 
using namespace std;

template class SharePtr;

template 
class ResPtr { // manage res of memory
private:
    T* res_p;    // point res
    int use_num; // count

    ResPtr(T *p) : res_p(p), use_num(1){
        cout << "the constructor of ResPtr\n";
    }
    ~ResPtr(){
        delete res_p;
        cout << "the destructor of ResPtr\n";
    }
    friend class SharePtr;
};

template
class SharePtr {
public:
    SharePtr(T *p, T i) : ptr(new ResPtr(p)), val(i){
        cout << "the constructor of SharePtr and the use count is " << ptr->use_num << endl;;
    }

    SharePtr(const SharePtr& rhs) : ptr(rhs.ptr), val(rhs.val) {
        ++ptr->use_num;
        cout << "the copy constructor of SharePtr and the use of count is " << ptr->use_num << endl;
    }

    ~SharePtr() {
        cout << "the destructor of SharePtr and the use of count is " << ptr->use_num << endl;
        if(--ptr->use_num == 0){
            cout << "relese memory\n";
            delete ptr;
        }
    }

    

    T &operator*(){
        return *this->ptr->res_p;
    }
    T *operator->(){
        return this->ptr->res_p;
    }


private:
    ResPtr *ptr; // point use_count
    T val;
};

// test code 
int main() {

    {
        SharePtr hpa = SharePtr{ new int (42), 100 };
        {
            // copy three objects
            SharePtr hpb{hpa};
            SharePtr hpc{hpb};
            SharePtr hpd{hpc};
        };
        cout << "inner end\n";
    }
    cout << "middle end\n";
    return 0;
}

  

你可能感兴趣的:(SmartPtr)