【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

转载于:https://www.cnblogs.com/visayafan/archive/2011/11/24/2261921.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值