【C++】智能指针 auto_ptr

 

 

/*
  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 <visayafan[AT]gmail.com>

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

HTML generated by org-mode 6.33x in emacs 23

posted @ 2011-11-24 16:23  visayafan  阅读(403)  评论(0编辑  收藏  举报