智能指针的实现

#include 
#include 
using namespace std;

template 
class SharedPtr {
public:
    SharedPtr(T* ptr = nullptr) :
        ref_count_(new int(1)), ptr_(ptr), mutex_(new mutex()) {
        if (ptr) {
            *ref_count_ = 1;
        } else {
            *ref_count_ = 0;
        }
    }
    ~SharedPtr() {
        Release();
    }
    SharedPtr(const SharedPtr& src) {
        ptr_ = src.ptr_;
        ref_count_ = src.ref_count_;
        mutex_ = src.mutex_;
        AddRefCount();
    }
    SharedPtr& operator=(const SharedPtr& src) {
        if (ptr_ != src.ptr_) {
            Release();
            ptr_ = src.ptr_;
            ref_count_ = src.ref_count_;
            mutex_ = src.mutex_;
            AddRefCount();
        }
        return *this;
    }
    T& operator*() {
        return *ptr_;
    }
    T* operator->() {
        return ptr_;
    }
    int UseCount() { return *ref_count_; }
    T* Get() { return ptr_; }

private:
    void AddRefCount() {
        mutex_->lock();
        ++ (*ref_count_);
        mutex_->unlock();
    }
    void Release() {
        bool delete_flag = false;
        mutex_->lock();
        if (--(*ref_count_) == 0) {
            delete_flag = true;
            delete ref_count_;
            delete ptr_;
        }
        mutex_->unlock();
        if (delete_flag) {
            delete mutex_;
        }
    }

    int* ref_count_;
    T* ptr_;
    mutex* mutex_;
};

int main() {
    SharedPtr p1(new int(10));
    SharedPtr p2(p1);
    SharedPtr p3;
    p3 = p2;
    cout << p1.UseCount() << endl;
    cout << p2.UseCount() << endl;
    cout << p3.UseCount() << endl;
    SharedPtr p4(new int(20));
    p3 = p4;
    cout << p3.UseCount() << endl;
    cout << p4.UseCount() << endl;
    return 0;
}

你可能感兴趣的:(智能指针的实现)