2016-09-30 14 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; 
}  
関連する問題