A Simple Reference Counting Smart Pointer Implementation

template <typename T>
class SharedPtr{
public:
    SharedPtr() = delete;//不允许未初始化的智能指针,防止使用空指针
    SharedPtr(const SharedPtr&) noexcept; //拷贝构造
    SharedPtr(const T*) noexcept; //shallow copy
    SharedPtr& operator=(const SharedPtr<T>) noexcept;//重载运算符
    ~SharedPtr();//析构函数
private:
    T *ptr;//原始指针
    int *use_count;//引用计数
};

template <typename T>
SharedPtr<T>::SharedPtr(const T* ptr) noexcept:ptr(ptr), use_count(new int(1))
{}

template <typename T>
SharedPtr<T>::SharedPtr(const SharedPtr &s_ptr) noexcept {
    ptr =s_ptr.ptr;
    use_count = s_ptr.use_count;
    ++(*use_count);
}

template <typename T>
SharedPtr<T>& SharedPtr<T>::operator=(const SharedPtr<T> rhs) noexcept {
    //待拷贝智能指针引用数加1
    ++(*rhs.use_count);

    //原智能指针引用计数减1,如果减一后引用计数为0就清楚所指向的资源
    if(0 == --(use_count)){
        delete ptr;
        delete use_count;
    }

    ptr = rhs.ptr;
    use_count = rhs.use_count;

    return *this;
}

template <typename T>
SharedPtr<T>::~SharedPtr(){
    if(0 == --(*use_count)){
        delete ptr;
        delete use_count;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325413844&siteId=291194637