智能指针

 

template <class T>
class SharedPtr
{
public:
    SharedPtr():ptr(new T()),count(new int(1)){}//无参构造
    explicit SharedPtr(T *src):ptr(str),count(new int(1)){}//有参构造
    explicit SharedPtr(T value):ptr(new T(value)),count(new int(1)){}//有参构造

    SharedPtr(const SharedPtr &rhs) :ptr(rhs.ptr), count(rhs.count)//拷贝构造
    {
        ++(*count);
    }

    SharedPtr& operator=(const SharedPtr &rhs)//赋值运算符
    {
        ++(*rhs.count);
        if (--(*count) == 0)
        {
            delete ptr;
            delete count;
        }
        ptr = rhs.ptr;
        count = rhs.count;
        return *this;
    }

    ~SharedPtr()
    {
        if (--(count) == 0)
        {
            delete ptr;
            delete count;
        }
    }

    T* get() const //获取资源
    {
        return ptr;
    }
private:
    T *ptr;//原始指针
    int *count;//引用计数
};

 

posted @ 2019-05-23 20:19  前进的code  阅读(167)  评论(0编辑  收藏  举报