#include<iostream>
using namespace std;
template<typename T>
class my_auto_ptr
{
private:
T *m_ptr;
public:
my_auto_ptr():m_ptr(NULL)
{
}
my_auto_ptr(T* ptr):m_ptr(ptr)
{
}
~my_auto_ptr() throw()
{
delete m_ptr;
m_ptr = NULL;
}
my_auto_ptr(my_auto_ptr<T> &ptr)
{
m_ptr = ptr.Release();
}
my_auto_ptr<T> & operator = ( my_auto_ptr<T> &ptr)
{
//看是否是自己
if(m_ptr == ptr.Get())
{
return (*this);
}
//删除原来的东西
if(m_ptr)
{
delete m_ptr;
m_ptr = NULL;
}
m_ptr = ptr.Release();
return (*this);
}
T & operator *()
{
return *m_ptr;
}
T * operator->()
{
return m_ptr;
}
T *Release()
{
T* temp = m_ptr;//将类中的指针保存起来
m_ptr = NULL;//将自己的指针赋空
return temp;//返回保存的指针
}
T *Get()
{
return m_ptr;
}
};
int main()
{
int *temp = new int (1234);
my_auto_ptr<int> intPtr(temp);
my_auto_ptr<int> intPP;
intPP = intPtr;
cout<<*intPP<<endl;
cout<<*intPtr<<endl;
system("pause");
return 0;
}
智能指针auto_ptr
最新推荐文章于 2025-03-06 20:22:14 发布