STL学习之auto_ptr

    C++标准程序库提供的auto_ptr是一种智能型指针,帮助程序员防止”被异常抛出时发生资源泄漏“。

1、auto_ptr的初始化

template <class _Tp> class auto_ptr {
private:
  _Tp* _M_ptr;

public:
  typedef _Tp element_type;

  explicit auto_ptr(_Tp* __p = 0) __STL_NOTHROW : _M_ptr(__p) {}
  auto_ptr(auto_ptr& __a) __STL_NOTHROW : _M_ptr(__a.release()) {}

#ifdef __STL_MEMBER_TEMPLATES
  template <class _Tp1> auto_ptr(auto_ptr<_Tp1>& __a) __STL_NOTHROW
    : _M_ptr(__a.release()) {}
#endif /* __STL_MEMBER_TEMPLATES */
上面是STL源代码中class auto_ptr定义的一部分,由上面可以看出一般指针的初始化式不适应于auto_ptr。

auto_ptr可能的初始化式如下:

std::auto_ptr<ClassA> ptr1(new ClassA);//OK
std::auto_ptr<ClassA> ptr2(ptr1);//OK
std::auto_ptr<ClassA> ptr3 = new ClassA;//ERROR

2、auto_ptr的所有权问题

C++标准程序库中规定了一个对象只能被一个auto_ptr对象拥有。

std::auto_ptr<ClassA> ptr1(new ClassA);
std::auto_ptr<ClassA> ptr2(ptr1);//ptr1不再拥有new出来的ClassA对象,所有权转移给ptr2
这点在将auto_ptr作为参数转递给函数时尤为重要,因为这样会导致原来的auto_ptr不再所有之前的对象,后期如果有针对该对象的类的操作,就会发生错误。

void fun(std::auto_ptr<ClassA> p)
{
	//do-something

}
int main()
{
	std::auto_ptr<ClassA> ptr(new ClassA);
	fun(ptr);//当fun运行时,ptr已经不再拥有new出来的ClassA
	//do-something on ptr
	    //这时如果再在ptr上操作就会发生错误
}

3、使用const 限定符来禁止所有权的转移

将auto_ptr加上const限定符后对象的所有权就不能再转移了。另外需要指出的是这里的关键词只是说明不能更改auto_ptr的拥有权,但是可是更改其所拥有的对象。

void fun(const std::auto_ptr<ClassA> p)
{
	//do-something

}
int main()
{
	const std::auto_ptr<ClassA> ptr(new ClassA);
	fun(ptr);//当fun运行时,ptr仍然拥有new出来的ClassA
	//do-something on ptr
	    //这时继续操作ptr就不会出错
	ClassA m;
	*ptr = m;//可以改ptr所拥有的对象
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值