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

发布时间 2023-09-22 16:59:24作者: C111-CR
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;
    }
};