首页 > 其他 > 详细

智能指针的简单实现

时间:2019-09-01 10:39:56      阅读:96      评论:0      收藏:0      [点我收藏+]
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");
    }
};

 

智能指针的简单实现

原文:https://www.cnblogs.com/zuofaqi/p/11441275.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!