zoukankan      html  css  js  c++  java
  • 手写一个shared_ptr智能指针

    手写一个shared_ptr智能指针

    #include <iostream>
    #include <cstdlib>
    using namespace std;
    
    template <typename T>
    class SmartPointer{
    public:
        SmartPointer(T* ptr){
            ref = ptr;
            ref_count = (unsigned*)malloc(sizeof(unsigned));
            *ref_count = 1;
        }
        
        SmartPointer(SmartPointer<T> &sptr){
            ref = sptr.ref;
            ref_count = sptr.ref_count;
            ++*ref_count;
        }
        
        SmartPointer<T>& operator=(SmartPointer<T> &sptr){
            if (this != &sptr) {
                if (--*ref_count == 0){
                    clear();
                    cout<<"operator= clear"<<endl;
                }
                
                ref = sptr.ref;
                ref_count = sptr.ref_count;
                ++*ref_count;
            }
            return *this;
        }
        
        ~SmartPointer(){
            if (--*ref_count == 0){
                clear();
                cout<<"destructor clear"<<endl;
            }
        }
        
        T getValue() { return *ref; }
        
    private:
        void clear(){
            delete ref;
            free(ref_count);
            ref = NULL; // 避免它成为迷途指针
            ref_count = NULL;
        }
       
    protected:    
        T *ref;
        unsigned *ref_count;
    };
    
    int main(){
        int *ip1 = new int();
        *ip1 = 11111;
        int *ip2 = new int();
        *ip2 = 22222;
        SmartPointer<int> sp1(ip1), sp2(ip2);
        SmartPointer<int> spa = sp1;
        sp2 = spa; // 注释掉它将得到不同输出
        return 0;
    }
    
  • 相关阅读:
    站内信设计
    python 发送邮件例子
    mysql 索引相关知识
    一、mysql分表简单介绍
    redis 学习笔记三(队列功能)
    redis 学习笔记二 (简单动态字符串)
    redis 学习笔记一
    docker部署asp.net core
    win10安装docker
    页面格式化后台的传过来的
  • 原文地址:https://www.cnblogs.com/buerdepepeqi/p/12461343.html
Copyright © 2011-2022 走看看