码迷,mamicode.com
首页 > 编程语言 > 详细

C++ 智能指针shared_ptr的实现

时间:2018-10-04 08:51:04      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:ret   temp   cout   lse   smart   函数   main   art   this   

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

  

C++ 智能指针shared_ptr的实现

标签:ret   temp   cout   lse   smart   函数   main   art   this   

原文地址:https://www.cnblogs.com/xuelisheng/p/9739812.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!