C++對(duì)象內(nèi)存模型
由于種種原因,我們無法保證所有通過new在heap中申請(qǐng)的內(nèi)存資源都安全地得到釋放,例如:
class base{...};
void f()
{
base* ptr = new base;
...
delete ptr;
}
這樣一系列操作中,在"..."中可能會(huì)拋出異常,最終導(dǎo)致delete無法得到執(zhí)行,于是就造成了內(nèi)存泄露。盡管我們可以設(shè)法避免在"..."中拋出異常,但是,對(duì)于后來維護(hù)和修改這段代碼了人員來說,很可能加入一些控制流,從而過早地從函數(shù)從中返回,內(nèi)存泄露再次發(fā)生。
一種解決之道就是,將資源封裝在一個(gè)類中,利用類的析構(gòu)函數(shù)來釋放該資源,這樣一來,無論是何種方式退出f()函數(shù)的作用域,類的析構(gòu)函數(shù)總是會(huì)被調(diào)用,從而有效地避免了資源泄露。
auto_ptr就是這種方法的一種典型應(yīng)用。它被稱為智能指針,是一個(gè)模板類。聲明一個(gè)只能指針的方法是: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++編譯器的輸出結(jié)果如下:
~$ g++ test.cpp -o test
~$ ./test
test_org():
demo()
test_auto():
demo()
~demo()
posted on 2009-03-11 14:36 pear_li 閱讀(286) 評(píng)論(0) 編輯 收藏 引用 所屬分類: C++