码迷,mamicode.com
首页 > 其他好文 > 详细

智能指针的简单实现

时间:2019-09-01 10:35:06      阅读:64      评论:0      收藏:0      [点我收藏+]

标签:size_t   bsp   ptr   div   ==   指针   let   lease   size   

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

 

智能指针的简单实现

标签:size_t   bsp   ptr   div   ==   指针   let   lease   size   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!