2016-09-30 69 views
1

下面的代碼是否表示內存泄漏?在C++類的構造函數中拋出異常

不調用Test類的析構函數(屏幕上沒有輸出),我假設所有分配給Int類數組的內存都不會返回給系統?我的假設是否正確?如果發生異常,我應該如何聲明在構造函數中分配的資源?

#include <iostream> 
using namespace std; 

class Int{ 
    public: 
     int v; 
     Int(){ 
     cout<<"inside Int constructor ..."<<endl; 
     } 

     ~Int(){ 
     cout<<"inside Int destructor ..."<<endl; 
     } 
}; 

class Test{ 
    public: 
    Int* a; 

    Test(){ 
     a=new Int[10]; 
     cout<<"inside Test constructor ..."<<endl; 
     throw(0); 
    } 

    ~Test(){ 
     delete [] a; 
     cout<<"inside Test destructor ..."<<endl; 
    } 
}; 

int main(){ 
    try{ 
     Test T; 
    } 
    catch (int e){ 
     cout<<"Error!!!"<<endl; 
    } 

    return 0; 
}  

回答

1

析構函數未被調用,因爲該對象從未完全構造。在部分構造的對象上調用它可能會更危險,因爲它會試圖消除從未完成的事情。作爲一名程序員,確保沒有內存(或任何其他資源)在構造函數中發生異常時會泄漏。

但是,將會調用基類和成員變量的析構函數!這就是爲什麼在大多數情況下最好依靠智能指針或容器來處理資源管理。嘗試改變你這樣的課程:

#include <memory> 

class Test{ 
    public: 
    std::unique_ptr<Int[]> a; 

    Test(){ 
     a=std::make_unique<Int[]>(10); 
     cout<<"inside Test constructor ..."<<endl; 
     throw(0); 
    } 

    ~Test(){ 
     //no need to delete[] a; 
     cout<<"inside Test destructor ..."<<endl; 
    } 
}; 

這是一個雙贏的局面。您將看到Int的析構函數將被調用,並且您不需要手動處理內存。

0

我想出了一個解決方案,但不知道這是一個好的設計或正確的方法來做到這一點。你能評論嗎?

#include <iostream> 
using namespace std; 

class Int{ 
    public: 
    int v; 
    Int(){ 
     cout<<"inside Int constructor ..."<<endl; 
    } 

     ~Int(){ 
     cout<<"inside Int destructor ..."<<endl; 
    } 
}; 

class Test{ 
    public: 
    Int* a; 

    Test(){ 
     try{ 
      a=new Int[10]; 
      cout<<"inside Test constructor ..."<<endl; 
      throw(0); // exception is thrown 
      } 

     catch (int e){ 
       delete [] a; 
       cout<<"Error!!!"<<endl; 
      } 
     } 

    ~Test(){ 
     delete [] a; 
     cout<<"inside Test destructor ..."<<endl; 
    } 
}; 

int main(){ 

     Test T; 


     return 0; 
}  
相關問題