C++ | 智能指针 模仿实现shared_ptr

template<class T>
class Shared_pointer{
private:
    ssize_t *_ref_count;    // 计数器的指针
    T *_ptr;                // 元素的指针
    std::mutex *mtx;        // 计数器的锁

public:
    explicit Shared_pointer(T *ptr = nullptr) 
        : _ptr(ptr), _ref_count(new ssize_t(1)), mtx(new std::mutex) 
    {}
    explicit Shared_pointer(const Shared_pointer<T> & sp) 
        : _ptr(sp._ptr), _ref_count(sp._ref_count), mtx(sp.mtx)
    {
        std::lock_guard<std::mutex> lg(*mtx);
        ++(*_ref_count);
    }
    ~Shared_pointer(){
        std::lock_guard<std::mutex> lg(*mtx);
        if(--(*_ref_count) == 0){
            delete _ref_count;
            delete _ptr;
            delete mtx;
        }
    }

    ssize_t use_count(){ return *_ref_count; }

    T* operator->(){
        return _ptr;
    }
    T& operator*(){
        return *_ptr;
    }
    Shared_pointer<T>& operator=( Shared_pointer<T> &other ){
        std::unique_lock<std::mutex> ul(this->mtx);
        // 析构掉当前对象
        if(this->_ptr && --(*_ref_count) == 0){
            delete _ref_count;
            delete _ptr;
            delete mtx;
        }
        ul.unlock();

        std::lock_guard<std::mutex> lg(other.mtx);
        // 用对象other给当前对象赋值
        this->_ptr = other._ptr;
        this->_ref_count = &(++(*other._ref_count));
        this->mtx = other.mtx;

        return *this;
    }
};
posted @   C111-CR  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示