C++11手写 shared_ptr,

#include <iostream>
#include <memory>
#include <mutex>

template<class T>
class Shared_Ptr {
public:
    Shared_Ptr(T *ptr = nullptr) : _pPtr(ptr), _pRefCount(new T()), _pMutex(std::make_shared<std::mutex>()) {}

    ~Shared_Ptr() {
        std::cout << "~Shared_Ptr" << std::endl;
        Release();
    }

    Shared_Ptr(const Shared_Ptr<T> &sp) : _pPtr(sp._pPtr), _pRefCount(sp._pRefCount), _pMutex(sp._pMutex) {
        AddRefCount();
    }

    Shared_Ptr<T> &operator=(const Shared_Ptr<T> &sp) {
        if (this != &sp) {
            Release();
            swap(*this, sp);
            AddRefCount();
        }
        return *this;
    }

    Shared_Ptr(Shared_Ptr<T> &&sp) noexcept {
        swap(*this, sp);
        sp._pPtr = nullptr; 
        sp._pRefCount = nullptr; 
    }

    Shared_Ptr<T> &operator=(Shared_Ptr<T> &&sp) noexcept {
        swap(*this, sp);
        sp._pPtr = nullptr;
        sp._pRefCount = nullptr; 
        return *this;
    }

    T &operator*() {
        return *_pPtr;
    }

    T *operator->() {
        return _pPtr;
    }

    int useCount() const {
        return _pRefCount ? *_pRefCount : 0;
    }

    T *get() const {
        return _pPtr;
    }

private:
    void AddRefCount() {
        if (_pRefCount)
        {
            std::lock_guard<std::mutex> lock(*_pMutex);
            ++(*_pRefCount);
        }
    }

    void Release() {
        if (_pRefCount)
        {
            std::lock_guard<std::mutex> lock(*_pMutex);
            if (--(*_pRefCount) == 0) {
                delete _pPtr;
                delete _pRefCount;
            }
        }
    }

    friend void swap(Shared_Ptr<T> &lhs, Shared_Ptr<T> &rhs) noexcept {
        using std::swap;
        swap(lhs._pPtr, rhs._pPtr);
        swap(lhs._pRefCount, rhs._pRefCount);
        swap(lhs._pMutex, rhs._pMutex);
    }

private:
    int *_pRefCount;
    T *_pPtr;
    std::shared_ptr<std::mutex> _pMutex;
};

int main() {
    Shared_Ptr<int> ptr(new int(42));
    std::cout << "use count: " << ptr.useCount() << std::endl;

    Shared_Ptr<int> ptr2 = std::move(ptr);
    std::cout << "use count after move: " << ptr.useCount() << std::endl;

    return 0;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值