• C++ 智能指针shared_ptr的实现


    #include <memory>
    #include <iostream>
    using namespace std;
    
    template<typename T>
    class smart{
    private:
        T* _ptr;
        int* _count; //reference counting
    public:
        //构造函数
        smart(T* ptr = nullptr):_ptr(ptr){
            if (_ptr){
                _count = new int(1);
            }
            else{
                _count = new int(0);
            }
        }
        
        //拷贝构造
        smart(const smart& ptr){
            if (this != &ptr){
                this->_ptr = ptr._ptr;
                this->_count = ptr._count;
                
                (*this->_count)++;
            }
        }
        
        //重载operator=
        smart operator=(const smart& ptr){
            if (this->_ptr == ptr._ptr){
                return *this;
            }
            if (this->_ptr){
                (*this->_count)--;
                if (this->_count == 0){
                    delete this->_ptr;
                    delete this->_count;
                }
            }
            this->_ptr = ptr._ptr;
            this->_count = ptr._count;
            (*this->_count)++;
            return *this;
        }
        
        //operator*重载
        T& operator*(){
            if (this->_ptr){
                return *(this->_ptr);
            }
        }
        
        //operator->重载
        T& operator->(){
            if (this->_ptr){
                return this->_ptr;
            }
        }
        //析构函数
        ~smart(){
            (*this->_count)--;
            if (*this->_count == 0){
                delete this->_ptr;
                delete this->_count;
            }
        }
        //return reference counting
        int use_count(){
            return *this->_count;
        }
    };
    
    int main(){
        smart<int> sm(new int(10));
        cout << "operator*():" << *sm << endl;
        cout << "reference counting:(sm)" << sm.use_count() << endl;
        smart<int> sm2(sm);
        cout <<"copy ctor reference counting:(sm)"<< sm.use_count() << endl;
        smart<int> sm3;
        sm3 = sm;
        cout <<"copy operator= reference counting:(sm)"<< sm.use_count() << endl;
        cout << &sm << endl;
        return 0;
    }
    

      

  • 相关阅读:
    开课博客
    第二周学习进度
    django新建项目
    装饰器执行顺序问题
    Python3 图片转字符画
    python项目
    jdbc url写法(集群)
    gradle执行test任务报错
    java.lang.NoClassDefFoundError: org/junit/runner/manipulation/Filter
    django 403问题
  • 原文地址:https://www.cnblogs.com/xuelisheng/p/9739812.html
Copyright © 2020-2023  润新知