smart_ptr智能指针的简单实现

来源:互联网 发布:网络公关服务公司 编辑:程序博客网 时间:2024/06/05 18:38
//// Created by yudw on 2017/8/7.//#pragma oncenamespace yudw{    template <typename T>    class smart_pointer    {    public:        // 需要显示构造        explicit smart_pointer(T* p): p_(p), use_(new size_t(1)){}        // 拷贝构造        smart_pointer(const T &rhs): p_(rhs.p_), use_(rhs.use_){ ++*use_;}        // 析构函数        ~smart_pointer()        {            if(--*use_ ==0)            {                delete p_;            }        }        T* operator -> () const{ return p_;}        T& operator * () const{ return *p_;}    private:        T* p_;  // 指针        size_t* use_;   // 引用计数    };}