Simple implementation of smart pointers

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");
    }
};

 

Guess you like

Origin www.cnblogs.com/zuofaqi/p/11441275.html
Recommended