比较完善的多线程安全 shared_ptr实现

采用加锁来实现ref_count线程安全

#include <iostream>
#include <string>
#include <mutex>
#include <memory>
using namespace std;


template <class T>
class Shared_ptr {
public:
    Shared_ptr(T* p = nullptr) 
     : ptr_(p), p_mutex_(new mutex) 
    {
        if (p == nullptr)
            ref_count_ = new int(0);
        else
            ref_count_ = new int(1);
    }

    Shared_ptr(const Shared_ptr<T> &sp)
     : ptr_(sp.ptr_), ref_count_(sp.ref_count_), p_mutex_(sp.p_mutex_) 
    {
        addRefCount();
    }

    Shared_ptr<T>& operator= (const Shared_ptr<T> &sp) 
    {
        if (this != &sp) {
            release();
            ptr_ = sp.ptr_;
            ref_count_ = sp.ref_count_;
            p_mutex_ = sp.p_mutex_;
            addRefCount();
        }
        return *this;
    }

    ~Shared_ptr() 
    {
        release();
    }

    T& operator* ()  // no const
    {
        return *ptr_;
    }

    T* operator-> ()  //编译器处理为((sp.operator->())->xxx())
    {
        return ptr_;
    }

    int use_count() const 
    {
        int count;
        p_mutex_->lock();
        count = *ref_count_;
        p_mutex_->unlock();
        return count;
    }

    T* get() 
    {
        return ptr_;
    }
       
private:
    void addRefCount() const
    {
        p_mutex_->lock();
        ++(*ref_count_);
        p_mutex_->unlock();
    }

    void release() const
    {
        bool delete_flag = false;
        p_mutex_->lock();
        if (--(*ref_count_) <= 0) {
            delete ptr_;
            delete ref_count_;
            delete_flag = true;
        }
        p_mutex_->unlock();

        if (delete_flag)
            delete p_mutex_;

    }


private:
    T* ptr_;
    int* ref_count_;
    mutex* p_mutex_;

};

int main() {
    Shared_ptr<string> p;
    cout << p.use_count() << endl;
    Shared_ptr<string> p1(new string("good"));
    *p1 = "www";
    Shared_ptr<string> p2;
    p2 = p1;
    Shared_ptr<string> p3(p2);

    cout << p1.use_count() << endl;
    cout << p.use_count() << endl;
    cout << *p2 << endl;




    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值