智能指针 shared_ptr 简易实现(C++)

template <typename T>
class shared_ptr {
private:
    int* count; // 引用计数,不同shared_ptr指向同一引用计数
    T* ptr; // 模板指针ptr,不同shared_ptr指向同一对象

public: 
    // 构造函数
    shared_ptr(T* p) : count(new int(1)), ptr(p) {}

    // 复制构造函数,引用计数+1
    shared_ptr(shared_ptr<T>& other) : count(&(++* other.count)), ptr(other.ptr) {}

    T* operator->()  return ptr;
    T& operator*()  return *ptr;

    // 赋值操作符重载
    shared_ptr<T>& operator=(shared_ptr<T>& other) {
        ++* other.count;
        // 如果原shared_ptr已经指向对象
        // 将原shared_ptr的引用计数-1,并判断是否需要delete
        if (this->ptr &&  -- *this->count==0 ) {
            delete count;
            delete ptr;
        }
        // 更新原shared_ptr
        this->ptr = other.ptr;
        this->count = other.count;
        return *this;
    }

    // 析构函数
    ~shared_ptr() {
        // 引用计数-1,并判断是否需要delete
        if (-- * count == 0) {
            delete count;
            delete ptr;
        }
    }

    // 获取引用计数
    int getRef()  return *count;
};
原文地址:https://www.cnblogs.com/yongjin-hou/p/15203761.html