C++实现shared_ptr

35 阅读1分钟
#include <iostream>

template<typename T>
class SharedPtr {
private:
    T* ptr;
    size_t* refCount;

public:
    SharedPtr(T* p = nullptr) : ptr(p), refCount(new size_t(1)) {}

    SharedPtr(const SharedPtr& other) : ptr(other.ptr), refCount(other.refCount) {
        (*refCount)++;
    }

    SharedPtr(SharedPtr&& other) noexcept : ptr(other.ptr), refCount(other.refCount) {
        other.ptr = nullptr;
        other.refCount = nullptr;
    }

    ~SharedPtr() {
        if (refCount && --(*refCount) == 0) {
            delete ptr;
            delete refCount;
        }
    }

    SharedPtr& operator=(const SharedPtr& other) {
        if (this!= &other) {
            if (--(*refCount) == 0) {
                delete ptr;
                delete refCount;
            }
            ptr = other.ptr;
            refCount = other.refCount;
            (*refCount)++;
        }
        return *this;
    }

    SharedPtr& operator=(SharedPtr&& other) noexcept {
        if (this!= &other) {
            std::swap(ptr, other.ptr);
            std::swap(refCount, other.refCount);
        }
        return *this;
    }

    T& operator*() const { return *ptr; }
    T* operator->() const { return ptr; }

    size_t use_count() const { return refCount? *refCount : 0; }
};

int main() {
    SharedPtr<int> sp1(new int(42));
    SharedPtr<int> sp2 = sp1;

    std::cout << "Use count of sp1: " << sp1.use_count() << std::endl; 
    std::cout << "Use count of sp2: " << sp2.use_count() << std::endl; 

    return 0;
}