智能指针的简单实现

template <class T>
class Sp {
public:
    Sp(T* ptr = nullptr) : ptr_(ptr), count_(new size_t) {
        if (ptr) {
            *count_ = 1;
        } else {
            *count_ = 0;
        }
    }

    Sp(const Sp& other) {
        ptr_ = other.ptr_;
        count_ = other.count_;
        (*count_)++;
    }

    Sp& operator=(const Sp& src) {
        if (ptr_ == src.ptr_) {
            return *this;
        }
        ReleaseCount();
        ptr_ = src.ptr_;
        count_ = src.count_;
        (*count_)++;
        return *this;
    }

    size_t use_count() {
        return *count_;
    }

    T& operator*() {
        if (ptr_)
        {
            return *ptr_;
        }
    }

    T* operator->() {
        if (ptr_)
        {
            return ptr_;
        }
    }

    operator bool() const {
        return ptr_ != nullptr;
    }

    ~Sp() {
        ReleaseCount();
    }

private:
    void ReleaseCount() {
        if (ptr_) {
            (*count_)--;
            if (*count_ == 0) {
                delete ptr_;
                delete count_;
            }
        }
    }

    T* ptr_ {nullptr};
    size_t* count_ {nullptr};
};

class Base
{
public:
    Base() {
        printf("con\n");
    }
    ~Base() {
        printf("decon\n");
    }
};

 

posted @ 2019-09-01 02:36  二狗啸地  阅读(247)  评论(0编辑  收藏  举报