auto_ptr 使用詳解 (C++98)
auto_ptr 是c++ 98定義的智能指針模板,其定義了管理指針的對象,可以將new 獲得(直接或間接)的地址賦給這種對象。當對象過期時,其析構函數將使用delete 來釋放內存!
用法:
頭文件: #include <memory>
用 法: auto_ptr<類型> 變量名(new 類型)
例 如:
auto_ptr str(new string(“我要成爲大牛~ 變得很牛逼!”));
auto_ptr<vector> av(new vector(10));
demo 代碼(一)
#include <iostream>
#include <string>
#include <exception>
#include <memory>
using namespace std;
// auto_ptr<Test>t(new Test()); /* 忠告1: 智能指針不要定義爲全局變量 */
class Test
{
public:
Test()
{
cout << "Test is construct" << endl;
this->debug = 1;
}
int getDebug()
{
return debug;
}
private:
int debug;
};
/* 用法: auto_ptr<類型> 變量名(new 類型) */
void memory_leak_demo1()
{
auto_ptr<Test>t(new Test());
/* 忠告3: 除非自己知道後果, 不要把 auto_ptr 智能指針賦值給同類型的另外一個智能指針 */
//auto_ptr<Test> t1;
//t1 = t;
auto_ptr<Test>* tp = new auto_ptr<Test>(new Test()); /* 忠告2: 不要定義指向智能指針對象的指針變量 */
/* 在使用智能指針訪問對象時, 使用方式和普通指針一樣 */
cout << "debug: " << t->getDebug() << endl;
cout << "debug: " << (*t).getDebug() << endl;
//Test* tmp = t.get();
//cout << "get debug: " << tmp->getDebug() << endl;
/* release 取消指針指針對動態內存的託管, 之前分配的內存必須手動釋放 */
//Test* tmp = t.release();
//delete tmp;
/* reset 重疊智能指針託管的內存地址, 如果地址不一致, 原來的會被析構調 */
//t.reset();
t.reset(new Test());
if (0)
{
Test* t1 = new Test();
t1->getDebug();
}
return;
}
int memory_leak_demo2()
{
Test* t = new Test();
auto_ptr<Test> t(new Test());
/*****************************************
* 程序執行一段複雜的邏輯, 假設嘗試從一個必須存在
* 的文件中讀取某些數據, 而文件此時不存在
******************************************/
{
throw exception("文件不存在");
}
//delete t;
return 0;
}
int main()
{
memory_leak_demo1();
/*try
{
memory_leak_demo2();
}
catch (exception e)
{
cout << "catch exception: " << e.what() << endl;
}*/
system("pause");
return 0;
}
使用建議:
- 儘可能不要將 auto_ptr 變量定義爲全局變量或指針
- 除非自己知道後果, 不要把 auto_ptr 智能指針賦值給同類型的另外一個智能指針
- C++11 後 auto_ptr 已經被 “被拋棄”, 已使用 unique_ptr 代替!
結語:
時間: 2020-07-03