由于種種原因,我們無法保證所有通過new在heap中申請的內存資源都安全地得到釋放,例如:
class base{...};
void f()
{
base* ptr = new base;
...
delete ptr;
}
這樣一系列操作中,在"..."中可能會拋出異常,最終導致delete無法得到執行,于是就造成了內存泄露。盡管我們可以設法避免在"..."中拋出異常,但是,對于后來維護和修改這段代碼了人員來說,很可能加入一些控制流,從而過早地從函數從中返回,內存泄露再次發生。
一種解決之道就是,將資源封裝在一個類中,利用類的析構函數來釋放該資源,這樣一來,無論是何種方式退出f()函數的作用域,類的析構函數總是會被調用,從而有效地避免了資源泄露。
auto_ptr就是這種方法的一種典型應用。它被稱為智能指針,是一個模板類。聲明一個只能指針的方法是:auto_ptr ptr(new T);為了說明auto_ptr的用法,下面是一個具體的例子:
#include <iostream>
#include <memory> //為了使用auto_ptr你必須包含頭文件:#include <memory>
using namespace std;
class demo
{
public:
demo ()
{
cout << "demo()" << endl;
}
~demo ()
{
cout << "~demo()" << endl;
}
};
void
test_org ()
{
cout << "test_org():" << endl;
demo *ptr = new demo;
return;
}
void
test_auto ()
{
cout << "test_auto():" << endl;
auto_ptr < demo > ptr (new demo);
return;
}
int
main (int narg, char **arg)
{
test_org ();
test_auto ();
return 0;
}
linux下,g++編譯器的輸出結果如下:
~$ g++ test.cpp -o test
~$ ./test
test_org():
demo()
test_auto():
demo()
~demo()