搜尋此網誌

2015年3月19日 星期四

How to use auto_ptr to avoid memory leak

Memory leak一直是程式debug的其中一項難題。
在C++中一項常見的錯誤就是new之後忘了delete,而導致此記憶體沒被回收重新使用。

Example:

void test()
{
    int* ptr = new int[5];
    // 一些操作後
}

void main()
{
    test();
}

上述的例子,是在說明當你使用function member或者function call去操作new出來的記憶體,卻忘了在程式最後去delete掉,將記憶體還回去,而此pointer在function結束後也沒辦法操作了,因此就造成了memory leak。

依照C++98的定義裡面介紹了auto_ptr就是用來解決此問題。
使用方式很簡單如下

auto_ptr<T> test(new T); //其中T代表任何資料型別
因此當test 的生命週期結束的時候,自然test會被回收使用

然而 auto_ptr有幾項缺點
1. auto_ptr當作參數傳給function時,在function結束後記憶體會被回收,原本的記憶體在主程式上就沒辦法被使用了。
2. auto_ptr不能使用在array,會有runtime error
3. auto_ptr不能使用在標準容器如vector, list, map...等等

Example1: 會在main()裡面的cout 出現crash,因為記憶體已經在Fun這個function結束被回收。
//***************************************************************
class Test
{
public:
 Test(int a = 0 ) : m_a(a)
 {
 }
 ~Test( )
 {
  cout<<"Calling destructor"<<endl;
 }
public:
 int m_a;
};
 
 
//***************************************************************
void Fun(auto_ptr<Test> p1 )
{
 cout<<p1->m_a<<endl;
}
//***************************************************************
void main( )
{
 std::auto_ptr<Test> p( new Test(5) ); 
 Fun(p);
 cout<<p->m_a<<endl;
} 

沒有留言:

張貼留言