c++智能指针:std::auto_ptr

简洁:由于 C++ 语言没有自动内存回收机制,程序员每次 new 出来的内存都要手动 delete。很容易造成内存泄漏或者多次delete崩溃。基于此问题,智能指针应运而生。
本文先来剖析标准库STL的智能指针auto_ptr.

用法如下:

#include <iostream>
#include <string>
#include <memory>
using namespace std;
class TestBody
{
public:
    TestBody(int param = 0):m_num(param)
    {
        m_info = "INFO";
        cout<<"construct TestBody"<<endl;
    }
    ~TestBody()
    {
        cout<<"destory TestBody"<<endl;
    }
    void SetInfo(string info)
    {
        m_info = info;
    }

    void PrintInfo()
    {
        cout<<"info:"<<m_info<<endl;
    }

private:
    int m_num;
    string m_info;
};
void TestAutoPtr1()
{
    auto_ptr<TestBody> smartPoint1(new TestBody(1));
    if(smartPoint1.get())
    {
        smartPoint1->PrintInfo();
        smartPoint1->SetInfo("TestAutoPtr1");
        smartPoint1->PrintInfo();
    }
}

int main(void)
{
    TestAutoPtr1();
    return 0;
}

结果如图:
这里写图片描述

下面例子:

void TestAutoPtr2()
{
    auto_ptr<TestBody> smartPoint1(new TestBody(1));
    if(smartPoint1.get())
    {
        smartPoint1->PrintInfo();
        auto_ptr<TestBody> smartPoint2 = smartPoint1;
        smartPoint2->PrintInfo();
        smartPoint1->PrintInfo();//直接崩溃
    }
}

跟进源码看,是赋值操作法的问题:auto_ptr smartPoint2 = smartPoint1;。smartPoint2 剥夺了 smartPoint1的控制权;

   template<typename _Tp1>auto_ptr&
   operator=(auto_ptr<_Tp1>& __a) throw()
   {
      reset(__a.release());
      return *this;
    }

    void reset(element_type* __p = 0) throw()
    {
       if (__p != _M_ptr)
      {
        delete _M_ptr;
        _M_ptr = __p;
      }
   }
  element_type* release() throw()
  {
    element_type* __tmp = _M_ptr;
    _M_ptr = 0;
    return __tmp;
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值