這篇文章不提任何的智能指針,看一段代碼、
示例一:
#include <iostream>
using namespace std;
class test
{
public:
test(){cout << "test()" << endl;}
~test(){cout << "~test()" << endl;}
};
int main()
{
test* ptr = new test();
for(int i = 0; i < 20; ++i)
{
if( i == 10)
return i;
}
delete ptr;
}
程序沒有運行到delete就結束了,導致堆上的對象沒有調用析構,資源沒有得到正確的釋放。
示例二:
#if 1
#include <iostream>
using namespace std;
class test
{
public:
test(){cout << "test()" << endl;}
~test(){cout << "~test()" << endl;}
};
template <class T>
class smart_ptr
{
public:
smart_ptr(T *ptr): _ptr(ptr){cout << "smart_ptr" << endl;}
~smart_ptr()
{
cout << "~smart_ptr" << endl;
delete _ptr;
}
T *_ptr;
};
int main()
{
smart_ptr<test> aptr(new test());
for(int i = 0; i < 20; ++i)
{
if( i == 10)
return i;
}
}
#endif
用類的特性,程序沒有崩,局部變量在return 函數結束的的時候會調用析構函數,而smart_ptr類裏的析構函數調用delete釋放資源
delete做了兩件事情
- 調用用析構函數
- 釋放內存