智能指针
用于缓解内存泄露的问题
用于替代原生指针
军规:只能指向堆空间中的对象或变量
方法
在智能指针的析构函数中调用delete
重载"->"操作符,只能重载成成员函数,且不能有参数
禁止智能指针的算术运算
一块对空间只能被一个智能指针指向
例子
#include<iostream>
#include<string> using namespace std; class Persion
{
string name;
int age;
public:
Persion(string name, int age)
{
this->name = name;
this->age = age;
cout<<"Persion()"<<endl;
} void show()
{
cout<<"name = "<<name<<endl;
cout<<"age = "<<age<<endl;
} ~Persion()
{
cout<<"~Persion()"<<endl;
}
}; template<typename T>
class Pointer
{
T* m_ptr;
public:
Pointer(T* ptr)
{
m_ptr = ptr;
} Pointer(const Pointer& other)
{
m_ptr = other.m_ptr;
const_cast<Pointer&>(other).m_ptr = NULL;
} Pointer& operator = (const Pointer& other)
{
if(this != &other)
{
if(m_ptr)
{
delete m_ptr;
} m_ptr = other.m_ptr;
const_cast<Pointer&>(other).m_ptr = NULL;
}
return *this;
} T* operator -> ()
{
return m_ptr;
} ~Pointer()
{
if(m_ptr)
{
delete m_ptr;
}
m_ptr = NULL;
}
}; int main()
{
Pointer<Persion> p = new Persion("zhangsan", );
Pointer<Persion> p1 = NULL;
p1 = p;
p1->show();
return ;
}