C++ 補充 & C++ 11 - C++智能指針

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章