一. 智能指针的基本作用
一句话带过:智能指针就是帮我们C++程序员管理动态分配的内存的,它会帮助我们自动释放new出来的内存,从而避免内存泄漏!
二. 一个内存泄露的例子
#include <iostream>
#include <memory>
#include <string>
class Test {
public:
Test()
{
std::cout << "Test的构造函数..." << std::endl;
}
~Test()
{
std::cout << "Test的析构函数..." << std::endl;
}
int getDebug()
{
std::cout << "just debug!" << std::endl;
return 0;
}
private:
int debug = 20;
};
int main() {
Test *test = new Test;
test->getDebug();
return 0;
}
终端输出:
Test的构造函数...
just debug!
为什么没有"析构"呢,内存泄露了吧,为什么呢?
因为代码中用new开辟了内存,但是程序结束时没有销毁内存,造成了内存泄露!
三. 用智能指针
#include <iostream>
#include <memory>
#include <string>
class Test {
public:
Test()
{
std::cout << "Test的构造函数..." << std::endl;
}
~Test()
{
std::cout << "Test的析构函数..." << std::endl;
}
int getDebug()
{
std::cout << "just debug!" << std::endl;
return 0;
}
private:
int debug = 20;
};
int main() {
std::shared_ptr<Test> test(new Test);
//std::shared_ptr<Test> test;
// test.reset(new Test); // 释放掉智能指针托管的指针内存,并将参数指针取代之
test->getDebug();
return 0;
}
终端输出:
Test的构造函数...
just debug!
Test的析构函数...
可以看到,用智能指针之后,就不用手动销毁内存了,也没有内存泄露!
参考:
https://blog.csdn.net/weixin_41504987/article/details/124396989
https://zhuanlan.zhihu.com/p/526147194?utm_id=0