C++補完&C++11-C++スマートポインタauto_ptr使用詳細(C++98)
auto_ptr使用詳細(C++98)
auto_ptrは、管理ポインタのオブジェクトを定義するc++98によって定義されたスマートポインタテンプレートであり、newが取得した(直接または間接的に)アドレスをこのオブジェクトに割り当てることができる.オブジェクトが期限切れになると、その解析関数はdeleteを使用してメモリを解放します.
使用法:ヘッダファイル:
例:auto_ptr str(new string);;auto_ptr av(new vector(10));
demoコード(一)
推奨事項:できるだけauto_をptr変数は、グローバル変数またはポインタ として定義される.自分が結果を知らない限りauto_ptrスマートポインタは、同じタイプの別のスマートポインタ に付与される. C++11後auto_ptrはすでに「捨てられた」、uniqueを使用している.ptr代替!
締めくくり:
時間:2020-07-03
auto_ptrは、管理ポインタのオブジェクトを定義するc++98によって定義されたスマートポインタテンプレートであり、newが取得した(直接または間接的に)アドレスをこのオブジェクトに割り当てることができる.オブジェクトが期限切れになると、その解析関数はdeleteを使用してメモリを解放します.
使用法:ヘッダファイル:
#include
使用法:auto_ptr変数名(newタイプ)例:auto_ptr str(new string);;auto_ptr av(new vector(10));
demoコード(一)
#include
#include
#include
#include
using namespace std;
// auto_ptrt(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 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;
}
推奨事項:
締めくくり:
時間:2020-07-03