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;
    }
    

      

  • 相关阅读:
    Java 的 多态和构造方法
    java 的 抽象类、接口
    java 的 封装 、继承
    eclipse的安装和基本使用、面向对象、类和对象
    方法的重载、引用数据类型、 ArrayList集合
    SQL单行函数
    JAVA
    mysql约束
    MYSQL的常用属性
    mysql的索引
  • 原文地址:https://www.cnblogs.com/xuelisheng/p/9739812.html
Copyright © 2011-2022 走看看