码迷,mamicode.com
首页 > 其他好文 > 详细

SmartPtr

时间:2020-01-10 23:50:34      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:struct   cts   poi   cout   point   stream   out   typename   operator   

// smart pointer implements


#include <iostream>
#include <memory>
using namespace std;

template<typename T> class SharePtr;

template<typename T> 
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<T>;
};

template<typename T>
class SharePtr {
public:
    SharePtr(T *p, T i) : ptr(new ResPtr<T>(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<T> *ptr; // point use_count
    T val;
};

// test code 
int main() {

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

  

SmartPtr

标签:struct   cts   poi   cout   point   stream   out   typename   operator   

原文地址:https://www.cnblogs.com/MasterYan576356467/p/12178486.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!