zoukankan      html  css  js  c++  java
  • 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;
    }
    

      

  • 相关阅读:
    luogu P2852 [USACO06DEC]Milk Patterns G
    FZOJ 4267 树上统计
    CF1303G Sum of Prefix Sums
    luogu P5311 [Ynoi2011]成都七中
    luogu P5306 [COCI2019] Transport
    SP34096 DIVCNTK
    luogu P5325 【模板】Min_25筛
    luogu P1742 最小圆覆盖
    求两直线交点坐标
    1098: 复合函数求值(函数专题)
  • 原文地址:https://www.cnblogs.com/xuelisheng/p/9739812.html
Copyright © 2011-2022 走看看