版权声明: https://blog.csdn.net/qq_40794602/article/details/85228744
- 如果有new出来的程序对象需要程序员自己去释放(delete)
- 有了智能指针,就可以让智能指针去托管这个对象,不用去担心内存泄露的问题
#include<iostream>
using namespace std;
class Test
{
public:
Test()
{
m_a = 999;
}
void show()
{
cout << "m_a:" << m_a << endl;
}
int m_a;
};
class smartPointer
{
public:
smartPointer(Test *p)
{
p_Test = p;
}
Test*& operator->()
{
return p_Test;
}
Test& operator*()
{
return *p_Test;
}
~smartPointer()
{
cout << "智能指针析构\n";
if (p_Test != NULL)
{
delete p_Test;
p_Test = NULL;
}
}
private:
Test* p_Test;
};
void test()
{
smartPointer p(new Test);
p->show(); //p->->show();编译器进行了优化
(*p).show();
}
int main()
{
test();
return 0;
}