模拟实现shared_ptr

来源:互联网 发布:批视频有哪些软件 编辑:程序博客网 时间:2024/05/22 03:51

模拟实现shared_ptr

template <class T>class sharedptr{public:sharedptr(T*ptr = NULL):_ptr(ptr), _pcount(NULL){if (_ptr != NULL){_pcount = new int(1);}}sharedptr(const sharedptr<T>&sp):_ptr(sp._ptr), _pcount(sp._pcount){*_pcount += 1;}sharedptr<T>& operator=(const sharedptr<T>&sp){if (_ptr != sp._ptr){//if (_pcount&&--*_pcount == 0)//当前对象独自管理空间//{//delete _ptr;//_ptr = NULL;//delete _pcount;//_pcount = NULL;//}//当前对象没有管理空间或者赋值者为nullrelese();_ptr = sp._ptr;_pcount = sp._pcount;if (_pcount != NULL){(*_pcount)++;}}return *this;}~sharedptr(){//if (_pcount != NULL&& --*_pcount == 0)//说明有对象并且只有一个对象管理空间//{//delete _ptr;//_ptr = NULL;//delete _pcount;//_pcount = NULL;//}relese();}T& operator*(){return *_ptr;}T operator->(){return _ptr;}private:void relese(){if (_pcount != NULL&& --*_pcount == 0)//说明有对象并且只有一个对象管理空间{delete _ptr;_ptr = NULL;delete _pcount;_pcount = NULL;}}private:T* _ptr;int* _pcount;};int main(){//sharedptr<int>sp1(new int);//sharedptr<int>sp2(sp1);sharedptr<int>sp3(new int);//sp3 = sp2;//当前对象独自管理一块空间//sp2 = sp3;//当前对象和sp1共享一块空间sharedptr<int>sp4;//sp4 = sp3;//当前对象没有管理空间sp3 = sp4;//空对象给有对象赋值system("pause");return 0;}


原创粉丝点击