C++中的智能指针

为什么要引入智能指针的概念

我们来看一个例子

void remodel(std::string & str)
{
    std::string * ps = new std::string(str);
    ...
    if (weird_thing())
        throw exception();
    str = *ps; 
    delete ps;
    return;
}

这个函数乍一看好像没问题,但是当出现异常时进入throw exception() 分支,delete将不会被执行,因此就造成了内存泄漏。

避免这种问题的方法:

  1. 直接在throw exception();之前加上delete ps;(适用于代码规模较小,逻辑较为清晰的的情况下)
  2. 设计一种随着指针生命周期结束自动释放指针指向内存的功能。

类似的问题还有

 int main()
 {
     int *ptr = new int(0); //假设内存申请不成功对异常的处理
     delete ptr; //释放后得指针会变成空悬指针野指针
     return 0;
 }

这时就引入了智能指针,智能指针主要解决了以下问题:

  1. 处理资源泄露的问题
  2. 处理空闲指针的问题
为什么C++11要舍弃auto_ptr

C++11从boost库中引入了unique_ptr, shared_ptr, weak_ptr, 同时舍弃了C89的auto_ptr
《C++标准程序库》描述:“auto_ptr是一种智能指针,帮助程序员防止’被异常抛出时发生资源泄露’”。
但是auto_ptr 有着严格的使用限制

  1. auto_ptr之间不能共享拥有权
  2. auto_ptr对象通过赋值或构造转移拥有权,一旦拥有权转移,此auto_ptr所拥有的将是一个原始指针
  3. auto_ptr不适用于array
  4. auto_ptr不满足STL对容器元素的要求,因此不适用于STL容器。因为在拷贝和赋值之后,新的auto_ptr和旧的auto_ptr对象并不相等。
  5. 如果要阻止拥有权的转移,则应该在停止转移之前,将auto_ptr声明为const
  6. 不要使用auto_ptr的引用作为实参:因为你不知道拥有权到底有没有转移。如果你不需要转移拥有权,请使用const auto_ptr<class> &

来看以下的几个例子
auto_ptr的初始化

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

auto_ptr拥有权转移

    //initialize an auto_ptr with a new obj
    std::auto_ptr<ClassA> ptr1(new ClassA);

    //copy the auto_ptr-->transfers the ownership from ptr1 to ptr2
    std::auto_ptr<ClassA> ptr2(ptr1);        //ptr1拥有权转移,以后不可再对ptr1使用operator*以及operator->

    //like copy
    std::auto_ptr<ClassA> ptr3 = ptr2;       //ptr2拥有权转移给ptr3,以后不可再对ptr2使用operator*以及operator->

    std::auto_ptr<ClassA> ptr4(new ClassA);  //create a new auto_ptr::ptr4
    ptr3 = ptr4;                             //here ptr3 delete the obj it own ,and then ptr4 transfers the ownership to ptr3。ptr4 own a nullptr

https://www.cnblogs.com/xiehongfeng100/p/4645555.html
http://www.cnblogs.com/lanxuezaipiao/p/4132096.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值