vs2008 中auto_ptr

来源:互联网 发布:齐鲁商品交易软件 编辑:程序博客网 时间:2024/06/08 13:17
// TEMPLATE CLASS auto_ptrtemplate<class _Ty>class auto_ptr;template<class _Ty>struct auto_ptr_ref{// proxy reference for auto_ptr copyingexplicit auto_ptr_ref(_Ty *_Right): _Ref(_Right){// construct from generic pointer to auto_ptr ptr}_Ty *_Ref;// generic pointer to auto_ptr ptr};template<class _Ty>class auto_ptr{// wrap an object pointer to ensure destructionpublic:typedef _Ty element_type;explicit auto_ptr(_Ty *_Ptr = 0) _THROW0(): _Myptr(_Ptr){// construct from object pointer}auto_ptr(auto_ptr<_Ty>& _Right) _THROW0(): _Myptr(_Right.release()){// construct by assuming pointer from _Right auto_ptr}auto_ptr(auto_ptr_ref<_Ty> _Right) _THROW0(){// construct by assuming pointer from _Right auto_ptr_ref_Ty *_Ptr = _Right._Ref;_Right._Ref = 0;// release old_Myptr = _Ptr;// reset this}template<class _Other>operator auto_ptr<_Other>() _THROW0(){// convert to compatible auto_ptrreturn (auto_ptr<_Other>(*this));}template<class _Other>operator auto_ptr_ref<_Other>() _THROW0(){// convert to compatible auto_ptr_ref_Other *_Cvtptr = _Myptr;// test implicit conversionauto_ptr_ref<_Other> _Ans(_Cvtptr);_Myptr = 0;// pass ownership to auto_ptr_refreturn (_Ans);}template<class _Other>auto_ptr<_Ty>& operator=(auto_ptr<_Other>& _Right) _THROW0(){// assign compatible _Right (assume pointer)reset(_Right.release());return (*this);}template<class _Other>auto_ptr(auto_ptr<_Other>& _Right) _THROW0(): _Myptr(_Right.release()){// construct by assuming pointer from _Right}auto_ptr<_Ty>& operator=(auto_ptr<_Ty>& _Right) _THROW0(){// assign compatible _Right (assume pointer)reset(_Right.release());return (*this);}auto_ptr<_Ty>& operator=(auto_ptr_ref<_Ty> _Right) _THROW0(){// assign compatible _Right._Ref (assume pointer)_Ty *_Ptr = _Right._Ref;_Right._Ref = 0;// release oldreset(_Ptr);// set newreturn (*this);}~auto_ptr(){// destroy the objectif (_Myptr != 0)delete _Myptr;}_Ty& operator*() const _THROW0(){// return designated value #if _HAS_ITERATOR_DEBUGGINGif (_Myptr == 0)_DEBUG_ERROR("auto_ptr not dereferencable"); #endif /* _HAS_ITERATOR_DEBUGGING */__analysis_assume(_Myptr);return (*get());}_Ty *operator->() const _THROW0(){// return pointer to class object #if _HAS_ITERATOR_DEBUGGINGif (_Myptr == 0)_DEBUG_ERROR("auto_ptr not dereferencable"); #endif /* _HAS_ITERATOR_DEBUGGING */return (get());}_Ty *get() const _THROW0(){// return wrapped pointerreturn (_Myptr);}_Ty *release() _THROW0(){// return wrapped pointer and give up ownership_Ty *_Tmp = _Myptr;_Myptr = 0;return (_Tmp);}void reset(_Ty* _Ptr = 0){// destroy designated object and store new pointerif (_Ptr != _Myptr && _Myptr != 0)delete _Myptr;_Myptr = _Ptr;}private:_Ty *_Myptr;// the wrapped object pointer};

原创粉丝点击