auto_ptr相关理解

本文解析了C++标准库中的auto_ptr模板类,探讨了其通过转移对象拥有权来实现资源管理的原理,并强调了通过const引用传递的正确用法,以防止意外行为。通过实例说明了byvalue传递的潜在风险和pass-by-reference的安全性。
摘要由CSDN通过智能技术生成

auto_ptr
auto_ptr采用的是一种弹性的解法:当auto_ptr被拷贝或被赋值,其【对象拥有权】会转移:

template<class T>
class auto_ptr{
public:
auto_ptr(auto_ptr<T>& rhs);
auto_ptr<T>& operator=(auto_ptr<T>& rhs);
}
template<class T>
auto_ptr<T>::auto_ptr(auto_ptr<T>& rhs)
{
pointee=rhs.pointee;
rhs.pointee=0;
};
template<class T>
auto_ptr<T>& auto_ptr<T>::operator=(auto_ptr<T>& rhs)
{
  if(this==&rhs)
  return *this;
  delete pointee;
  pointee=rhs.pointee;
  rhs.pointee=0;
  return *this;
};

注意assignment在掌握一个新对象的拥有权之前,必须先删除它所拥有的对象。

以by value方式传递auto_ptr是个容易出现错误的情况
例子:

void printTreeNode(ostream& s,auto_ptr<TreeNode> p)
{s<<*p;}
int main()
{
auto_ptr<TreeNode>ptn(new TreeNode);
prinTreeNode(cout,ptn);//以by value方式传递auto_ptr
//在此之后实用ptn都会导致未定义的行为
}

以pass-by-reference是安全的

void printTreeNode(ostream& s, const auto_ptr<TreeNode>& p)
{
     s<<*p;
     //保留零零ptn所指之物的拥有权
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值