1、vc++6.0下的auto_ptr源码如下:
-
template<class _Ty>
-
class auto_ptr {
-
public:
-
typedef _Ty element_type;
-
explicit auto_ptr(_Ty *_P = 0) _THROW0()
-
: _Owns(_P != 0), _Ptr(_P) {}
-
auto_ptr(const auto_ptr<_Ty>& _Y) _THROW0()
-
: _Owns(_Y._Owns), _Ptr(_Y.release()) {}
-
auto_ptr<_Ty>& operator=(const auto_ptr<_Ty>& _Y) _THROW0()
-
{if (this != &_Y)
-
{if (_Ptr != _Y.get())
-
{if (_Owns)
-
delete _Ptr;
-
_Owns = _Y._Owns; }
-
else if (_Y._Owns)
-
_Owns = true;
-
_Ptr = _Y.release(); }
-
return (*this); }
-
~auto_ptr()
-
{if (_Owns)
-
delete _Ptr; }
-
_Ty& operator*() const _THROW0()
-
{return (*get()); }
-
_Ty *operator->() const _THROW0()
-
{return (get()); }
-
_Ty *get() const _THROW0()
-
{return (_Ptr); }
-
_Ty *release() const _THROW0()
-
{((auto_ptr<_Ty> *)this)->_Owns = false;
-
return (_Ptr); }
-
private:
-
bool _Owns;
-
_Ty *_Ptr;
- };
实例代码如下:
-
#include<iostream>
-
#include<memory>
-
using namespace std;
-
-
class Simple
-
{
-
public:
-
Simple(int param)
-
{
-
number=param;
-
cout<<"Simple constructor:"<<number<<endl;
-
}
-
~Simple()
-
{
-
cout<<"~Simple:"<<number<<endl;
-
}
-
void PrintSomething()
-
{
-
cout<<"PrintSomething:"<<number<<endl;
-
}
-
-
int number;
-
};
-
-
void TestAutoPtr()
-
{
-
-
auto_ptr<Simple> my_memory(new Simple(1));
-
if(my_memory.get())
-
{
-
my_memory->PrintSomething();
-
my_memory.get()->PrintSomething();
-
cout<<(*my_memory).number<<endl;
-
}
-
Simple *ss= my_memory.release();
-
my_memory->PrintSomething();
-
ss->PrintSomething();
-
delete ss;
-
my_memory->PrintSomething();
-
ss->PrintSomething();
- ss=NULL;
-
}
-
-
int main()
-
{
-
TestAutoPtr();
-
return 0;
- }
delete p完成的事情:
delete函数释放堆上的内存,实际相当于p释放了对那片内存的使用权。然后系统的内存回收机制就会将那片区域重置
。
p=NULL;相当于将指针p的值置为空,使得p不再指向那块内存。