zoukankan      html  css  js  c++  java
  • SmartPtr

    // 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
    ";
        }
        ~ResPtr(){
            delete res_p;
            cout << "the destructor of ResPtr
    ";
        }
        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
    ";
                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
    ";
        }
        cout << "middle end
    ";
        return 0;
    }
    

      

  • 相关阅读:
    mysql语句
    jsp中调用javabean
    java内存分配
    BaseClasses学习(-)CAMEvent
    YUV格式入门
    gcc intrinsic vector
    GCC builtin vector (gcc内建函数)学习
    GNU 内联汇编学习(1)
    express 中间件
    《饿了么大前端 Node.js 进阶教程》—Javascript 基础问题—引用传递
  • 原文地址:https://www.cnblogs.com/MasterYan576356467/p/12178486.html
Copyright © 2011-2022 走看看