boost::shared_ptr与定制删除器
shared_ptr
shared_ptr是一种智能指针,他的作用如同指针,但会记录有多少shared_ptr指向同一个对象。使用时必须引用头文件<boost/shared_ptr.hpp>
template<classT>classShartedPtr{public://构造函数ShartedPtr(T*ptr):_ptr(ptr),_pCount(newint(1)){}//拷贝构造ShartedPtr(constShartedPtr<T>&sp):_ptr(sp._ptr),_pCount(sp._pCount){++(*_pCount);}//赋值ShartedPtr&operator=(ShartedPtr<T>sp){swap(_ptr,sp._ptr);swap(_pCount,sp._pCount);return*this;}//重载*T&operator*(){return*_ptr;}//重载->T*operator->(){return_ptr;}//析构函数~ShartedPtr(){Relase();}protected:voidRelase(){if(--(*_pCount)==0){delete_ptr;delete_pCount;}}private:T*_ptr;int*_pCount;};structA{int_A;};intmain(){ShartedPtr<int>sp1(newint(1));ShartedPtr<int>sp2(sp1);sp1=sp2;ShartedPtr<int>sp3(sp2);*sp3=10;ShartedPtr<A>sp4(newA);sp4->_A=30;return0;}
但是shared_ptr也存在一系列问题
引用计数存在线程安全问题
会出现循环引用问题
定制删除器
循环引用即在使用双向链表时,若使用shared_ptr则会出现在析构时由于同一块空间有两个对象指向,且对象两两之间相互指向,故在析构时两对象都在等对方的_pCount减为一,从而一直到最后对象都没有析构
shared_ptr<Node>cur(newNode(1));shared_ptr<Node>next(newNode(1));cur->_next=next;next->_prev=cur;
shared_ptr的定制删除器
template<classT,classD>classShartedPtr{public://构造函数ShartedPtr(T*ptr):_ptr(ptr),_pCount(newint(1)){}//构造函数的一个重载ShartedPtr(T*ptr,Ddel):_ptr(ptr),_pCount(newint(1)),_del(del){}//拷贝构造ShartedPtr(constShartedPtr<T,D>&sp):_ptr(sp._ptr),_pCount(sp._pCount){++(*_pCount);}//赋值ShartedPtr&operator=(ShartedPtr<T,D>sp){swap(_ptr,sp._ptr);swap(_pCount,sp._pCount);return*this;}//重载*T&operator*(){return*_ptr;}//重载->T*operator->(){return_ptr;}//析构函数~ShartedPtr(){Release();}protected:voidRelease(){if(--(*_pCount)==0){_del(_ptr);delete_pCount;}}private:T*_ptr;int*_pCount;D_del;};structDefaultDel{voidoperator()(void*ptr){deleteptr;}};structFree{voidoperator()(void*ptr){free(ptr);}};//structFclose//{//voidoperator()(void*ptr)//{//fclose(FILE*(ptr));//}//};intmain(){ShartedPtr<int,DefaultDel>sp1(newint(1));ShartedPtr<int,Free>sp2((int*)malloc(sizeof(int)));}
ps:仿函数的介绍
仿函数就是使一个类使用看上去像一个函数,其实现就是类中实现一个operator().这个类就有了类似函数的行为。
structFree{voidoperator()(void*ptr){free(ptr);}};voidTestsharedptr(){int*p1=(int*)malloc(sizeof(int)*10);shared_ptr<int>sp1(p1,Free());//在使用完后自动释放p1}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。