STL-auto_ptr
来源:互联网 发布:软件外包合同 英文 编辑:程序博客网 时间:2024/06/18 04:09
template<class _Ty>
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)
class auto_ptr ...{
public:
typedef _Ty element_type;
explicit auto_ptr(_Ty *_P = 0) _THROW0()
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
: _Owns(_P != 0), _Ptr(_P) ...{} //完成构造函数,主要有两个内容指针所有者,和ptr指针。
auto_ptr(const auto_ptr<_Ty>& _Y) _THROW0()
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
: _Owns(_Y._Owns), _Ptr(_Y.release()) ...{} //拷贝构造函数,并且owns变为this.owns指针所有者发生变化,y成为空指针。
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
auto_ptr<_Ty>& operator=(const auto_ptr<_Ty>& _Y) _THROW0()
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
...{if (this != &_Y)
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
...{if (_Ptr != _Y.get())
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
...{if (_Owns)
delete _Ptr;
_Owns = _Y._Owns; }
else if (_Y._Owns)
_Owns = true;
_Ptr = _Y.release(); }
return (*this); } //赋值构造函数,指针与y指针不同并且所有者存在,删除自己指针,赋值y的指针。所有者成为自己。
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
~auto_ptr()
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
...{if (_Owns)
delete _Ptr; } //析构函数若所有指针,则ptr=null;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)
_Ty& operator*() const _THROW0()
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
...{return (*get()); } //得到拥有的物件。
_Ty *operator->() const _THROW0()
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
...{return (get()); } //得到指针
_Ty *get() const _THROW0()
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
...{return (_Ptr); } //返回指针
_Ty *release() const _THROW0()
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
...{((auto_ptr<_Ty> *)this)->_Owns = false;
return (_Ptr); } //不再拥有物件,并且返回物件指针
private:
bool _Owns; //是否所有
_Ty *_Ptr; //指针
};
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)