本文主要是介绍Smart pointers,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Smart pointers基本模型template <class T>
class SmartPtr
{
public:
explicit SmartPtr(T* pointee):pointee_(pointee);
SmartPtr &operator=(const SmartPtr&other);
~SmartPtr();
T& operator*()const{
...
return *pointee_;
}
T* operator->()const{
...
return pointee_;
}
private:
T * pointee_;
...
}
class Widget
{
public:
void Fun();
};
SmartPtr<Widget>sp(new Widget);
sp->Fun();
(*sp).Fun();
Widget *p=new Widget;
p=0;//导致资源泄漏
因为具备value语义,所以避免bug,细分了很多种类的SmartPtr;
SmartPtr只保留必要的成员函数,以区分于类
template<class T>T * GetImpl(SmartPtr<T>&sp);
template<class T>T *& GetImplRef(SmartPtr<T>&sp);
template<class T>void Reset(SmartPtr<T>&sp ,T* source);
template<class T>void Release(SmartPtr<T>&sp,T*&destination);
SmartPtr 没有copy函数,而用Clone函数,以是Value语义具备继承多态特性
SmartPtr 引用计数采用双向链表存储,指向同一个对象
摧毁式拷贝
template<class T>
class SmartPtr
{
public:
SmartPtr(SmartPtr&src)
{
pointee_=src.pointee_;
src.pointee_=0;
}
SmartPtr&operator=(SmartPtr& src)
{
if(this != &src)
{
delete pointee_;
pointee_=src.pointee_;
src.pointee_=0;
}
return *this;
}
}
摧毁式拷贝不能存储于容器内,容易形成null指针
SmartPtr不重载unary operator&
SmartPtr拒绝隐式转换,可以显示手动转换接口
template<T>
class SmartPtr
{
public:
operator T*()
{
return pointee_;
}
operator void*()
{
return pointee_;
}
}
禁止delete SmartPtr
这篇关于Smart pointers的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!