Chinaunix首页 | 论坛 | 博客
  • 博客访问: 532477
  • 博文数量: 129
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1888
  • 用 户 组: 普通用户
  • 注册时间: 2013-06-20 11:09
文章分类

全部博文(129)

文章存档

2016年(1)

2015年(5)

2014年(64)

2013年(59)

我的朋友

分类: C/C++

2013-12-13 20:39:00

在我前面的有一篇博客中有队auto_ptr的源码及实例解析,但从摘抄的源码解析和我最后写的程序调试结果有诸多相悖的地方。于是查看了vc++6.0下的auto_ptr的源码(在memory下),重新理解一下auto_ptr。

1、vc++6.0下的auto_ptr源码如下:

  
  1. template<class _Ty>
  2.     class auto_ptr {
  3. public:
  4.     typedef _Ty element_type;
  5.     explicit auto_ptr(_Ty *_P = 0) _THROW0()
  6.         : _Owns(_P != 0), _Ptr(_P) {}
  7.     auto_ptr(const auto_ptr<_Ty>& _Y) _THROW0()
  8.         : _Owns(_Y._Owns), _Ptr(_Y.release()) {}
  9.     auto_ptr<_Ty>& operator=(const auto_ptr<_Ty>& _Y) _THROW0()
  10.         {if (this != &_Y)
  11.             {if (_Ptr != _Y.get())
  12.                 {if (_Owns)
  13.                     delete _Ptr;
  14.                 _Owns = _Y._Owns; }
  15.             else if (_Y._Owns)
  16.                 _Owns = true;
  17.             _Ptr = _Y.release(); }
  18.         return (*this); }
  19.     ~auto_ptr()
  20.         {if (_Owns)
  21.             delete _Ptr; }
  22.     _Ty& operator*() const _THROW0()
  23.         {return (*get()); }
  24.     _Ty *operator->() const _THROW0()
  25.         {return (get()); }
  26.     _Ty *get() const _THROW0()
  27.         {return (_Ptr); }
  28.     _Ty *release() const _THROW0()
  29.         {((auto_ptr<_Ty> *)this)->_Owns = false;
  30.         return (_Ptr); }
  31. private:
  32.     bool _Owns;
  33.     _Ty *_Ptr;
  34.     };


实例代码如下:
 
 
  1. #include<iostream>
  2. #include<memory>
  3. using namespace std;

  4. class Simple
  5. {
  6. public:
  7.     Simple(int param)
  8.     {
  9.         number=param;
  10.         cout<<"Simple constructor:"<<number<<endl;
  11.     }
  12.     ~Simple()
  13.     {
  14.         cout<<"~Simple:"<<number<<endl;
  15.     }
  16.     void PrintSomething()
  17.     {
  18.         cout<<"PrintSomething:"<<number<<endl;
  19.     }

  20.     int number;
  21. };

  22. void TestAutoPtr()
  23. {

  24.     auto_ptr<Simple> my_memory(new Simple(1));
  25.     if(my_memory.get())
  26.     {
  27.         my_memory->PrintSomething();
  28.         my_memory.get()->PrintSomething();
  29.         cout<<(*my_memory).number<<endl;
  30.     }
  31.     Simple *ss= my_memory.release();
  32.     my_memory->PrintSomething();
  33.     ss->PrintSomething();
  34.     delete ss;
  35.     my_memory->PrintSomething();
  36.     ss->PrintSomething();
  37.     ss=NULL;
  38. }

  39. int main()
  40. {
  41.     TestAutoPtr();
  42.     return 0;
  43. }

 


delete p完成的事情:
   delete函数释放堆上的内存,实际相当于p释放了对那片内存的使用权。然后系统的内存回收机制就会将那片区域重置



p=NULL;相当于将指针p的值置为空,使得p不再指向那块内存。


阅读(1138) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~