shared_ptr

来源:互联网 发布:站长工具js格式化 编辑:程序博客网 时间:2024/06/10 15:01
template <class T> class SmartPointer {public:    SmartPointer(T * ptr)     {        ref = ptr;        ref_count = (unsigned*)malloc(sizeof(unsigned));        *ref_count = 1;    }    SmartPointer(SmartPointer<T> & sptr)     {        ref = sptr.ref;        ref_count = sptr.ref_count;        ++*ref_count;    }       SmartPointer<T> & operator=(SmartPointer<T> & sptr)    {       if (this != &sptr)       {           ref = sptr.ref;           ref_count = sptr.ref_count;           ++*ref_count;        }        return *this;   }      ~SmartPointer()    {       --*ref_count;       if (*ref_count == 0)        {           delete ref;           free(ref_count);           ref = NULL;           ref_count = NULL;        }    }    T getValue() { return *ref; }protected:    T * ref;    unsigned * ref_count;};


 

0 0
原创粉丝点击