一个简单引用计数智能指针的实现


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

template <typename T>
SharedPtr<T>::SharedPtr(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 {
    //考虑自我赋值的情况
    if(rhs.ptr == this->ptr){
        return *this;
    }
    //待拷贝智能指针引用数加1
    ++(*rhs.use_count);

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

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

    return *this;
}

template <typename T>
T& SharedPtr<T>::operator*() noexcept{
    return *this->ptr;
}

template <typename  T>
T* SharedPtr<T>::operator->() noexcept{
    return this->ptr;
}

template <typename  T>
SharedPtr<T>::~SharedPtr(){
    if(0 == --(*use_count)){
        delete ptr;
        delete use_count;
    }
}
阅读更多
版权声明:本博客的所有内容采用Creative Commons(知识共享)许可证,作者权利:署名(BY)& 非商业性使用(NC)。转载时请务必标明文章超链接、作者信息和本声明,禁止用于商业用途。 https://blog.csdn.net/thinkerleo1997/article/details/80216561
个人分类: C/C++
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭