C++智能指针
为什么要使用智能指针
举个例子 demo 代码(一)
#include <iostream>
#include <string>
#include <exception>
using namespace std;
void memory_leak_demo1()
{
string* str = new string("今天写了一天代码, 太累了, 回家睡觉!!!");
cout << *str << endl;
return;
}
int memory_leak_demo2()
{
string* str = new string("这个世界到处是坑, 所以异常处理要谨记在心!!!");
/*****************************************
* 程序执行一段复杂的逻辑, 假设尝试从一个必须存在
* 的文件中读取某些数据, 而文件此时不存在
******************************************/
{
throw exception("文件不存在");
}
cout << *str << endl;
delete str;
return 0;
}
int main()
{
memory_leak_demo1();
try
{
memory_leak_demo2();
}
catch (exception e)
{
cout << "catch exception: " << e.what() << endl;
}
system("pause");
return 0;
}
以上两种情况都会出现内存泄漏!
修改 demo 代码(二)
更好的解决方案: 把string 定义为auto 变量,在函数生命周期结束时释放!
#include <iostream>
#include <string>
#include <exception>
using namespace std;
void memory_leak_demo1()
{
//string* str = new string("今天写了一天代码, 太累了, 回家睡觉!!!");
string str("今天写了一天代码, 太累了, 回家睡觉!!!");
cout << str << endl;
return;
}
int memory_leak_demo2()
{
//string* str = new string("这个世界到处是坑, 所以异常处理要谨记在心!!!");
string str("今天写了一天代码, 太累了, 回家睡觉!!!");
/*****************************************
* 程序执行一段复杂的逻辑, 假设尝试从一个必须存在
* 的文件中读取某些数据, 而文件此时不存在
******************************************/
{
throw exception("文件不存在");
}
cout << str << endl;
//delete str;
return 0;
}
int main()
{
memory_leak_demo1();
try
{
memory_leak_demo2();
}
catch (exception e)
{
cout << "catch exception: " << e.what() << endl;
}
system("pause");
return 0;
}
string 类, str(对象) 本身buff 动态内存分配, 它会自动释放
启发:
思考:
如果我们分配的动态内存都交由有生命周期的对象来处理,那么在对象过期时,让它的析构函数删除指向的内存,这看似是一个 very nice 的方案?
智能指针就是通过这个原理来解决指针自动释放的问题!
C++98 提供了 auto_ptr 模板的解决方案
C++11 增加unique_ptr、shared_ptr 和weak_ptr
结语:
时间: 2020-07-02