手撕智能指针shared_ptr

发布时间 2023-09-15 21:53:13作者: SuperTonyy
#include <bits/stdc++.h>
using namespace std;

class Count {
private:
    int cnt;
public:
    Count() :cnt(1) {}
    ~Count() = default;
    void addcount() { ++cnt; }
    int getcount() { return cnt; }
    int reducecount() { return --cnt; }
};

template <typename T>
class Shared_ptr {
private:
    T* ptr;
    Count* cnt;
public:
    //构造函数
    Shared_ptr(T* pt = nullptr) : ptr(pt) {
        if (pt)
            cnt = new Count();
    }

    //析构函数
    ~Shared_ptr() {
        if (ptr && !cnt -> reducecount()) {
            delete ptr;
            delete cnt;
        }
    }

    //拷贝构造函数
    Shared_ptr(Shared_ptr<T>& sptr) {
        ptr = sptr.ptr;
        if (ptr) {
            cnt = sptr.cnt;
            cnt -> addcount();
        }
    }

    //移动构造函数
    Shared_ptr(Shared_ptr<T>&& sptr) {
        ptr = sptr.ptr;
        if (ptr) {
            cnt = sptr.cnt;
            sptr.ptr = nullptr;
            sptr.cnt = nullptr;
        }
    }

    //拷贝构造运算符
    Shared_ptr& operator=(Shared_ptr& sptr) {
        ptr = sptr.ptr;
        if (ptr) {
            cnt = sptr.cnt;
            cnt -> addcount();
        }
        return *this;
    }

    Shared_ptr& operator=(Shared_ptr<T>&& sptr) {
        ptr = sptr.ptr;
        if (ptr) {
            cnt = sptr.cnt;
            sptr.ptr = nullptr;
            sptr.cnt = nullptr;
        }
        return *this;
    }

    long use_count() {
        if (ptr)
            return cnt -> getcount();
        return 0;
    }
};

int main() {

    Shared_ptr<int> p1(new int(10));
    cout << p1.use_count() << endl;
    Shared_ptr<int> p2(p1);
    cout << p2.use_count() << endl;
    return 0;
}