您的位置:首页 > 编程语言 > C语言/C++

【C++】智能指针 auto_ptr

2011-11-24 16:23 239 查看
/*
auto_ptr是智能指引,可以自我销毁而不像new出来的对象一样需要调用delete销毁。
auto_ptr赋值用引起所有权的交接,作为函数参数或返回值都会引起所有权的交接。
auto_ptr必须显示初始化
auto_ptr<int> p(new int(43)) //ok
auto_ptr<int> p = new int(43) //error
auto_ptr<int> p;
p = new int(43);      //error
p = auto_ptr<int>(43) //ok

auto_ptr的函数:
Type* release() throw();      //将该auto_ptr设为null,并且返回该对象的地址
void reset(TYPE *_ptr = 0);   //用来接收所有权,如果接收所有权者已经拥有了对象,则必须先释放该对象。其中_ptr是TYPE类型的指针,它将会替换原来auto_ptr所拥有的指针。
TYPE* get() const throw;      //返回该类存储的指针。
*/

#include <memory>
#include <iostream>
using namespace std;
class Int
{
public:
Int( int i ) {
x = i;
cout << "Constructing " << ( void* )this << " Value: " << x << endl;
};
~Int( ) {
cout << "Destructing " << ( void* )this << " Value: " << x << endl;
};
int x;
};
int main( )
{
auto_ptr<Int> pi ( new Int( 5 ) );
pi.reset( new Int( 6 ) );
Int* pi2 = pi.get ( );
Int* pi3 = pi.release ( );
cout<<pi.get()<<endl;
if ( pi2 == pi3 )
cout << "pi2 == pi3" << endl;
delete pi3;
}
/*
Constructing 0x3e2be8 Value: 5
Constructing 0x3e4af8 Value: 6
Destructing 0x3e2be8 Value: 5   //一个auto_ptr只能指向一个对象,所以在赋新值前先要销毁旧的。
0                               //调用release()后auto_ptr返回其存储值,并赋空,
pi2 == pi3                      //pi2与pi3都是原来pi存储类的指针。
Destructing 0x3e4af8 Value: 6
*/


Author: visaya fan gmail.com]<visayafan[AT]gmail.com>

Date: 2011-11-24 16:21:36

HTML generated by org-mode 6.33x in emacs 23
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: