2016-04-09 7 views
-1

我々はC++次のコードがあるとします。で構成される構造体のメモリを解放するための正しい方法

struct A 
{ 
    int* a; 
    A() 
    { 
     a = new int(5); 
    } 

    ~A() 
    { 
     delete a; 
    } 
}; 

struct B 
{ 
    A a; 
    int b; 

    B() 
    { 
     a = A(); 
     b = 10; 
    } 
}; 

int main() 
{ 
    B b; 

    return 0; 
} 

は、それを実行し、Aのデストラクタは二回と呼ばれるが、なぜます? Bの暗黙のデストラクタがBのメンバのすべてのデストラクタを呼び出すのは分かりますが、Aのデストラクタへの2回目の呼び出しはいつ起こりますか?そのような場合にメモリを処理する適切な方法は何ですか?

+1

debugerなくても手で、 はこれをデバッグしてください、あなたはもっと理解する: '= A();' –

答えて

0

データメンバーのコンストラクタは、クラスのコンストラクタで呼び出されます。初期化子リストを使用してコンストラクタを明示的に指定しない限り、すべてのメンバーのデフォルトコンストラクタがコンストラクタの最初の行に到達する前に呼び出されます。デストラクタがここで初めて呼び出されます

#include <iostream> 
#include <stdlib.h> 
struct A 
{ 
    int* a; 
    A() 
    { 
     a = new int(5); 
     std::cout<<"A()"<<std::endl; 
    } 

    ~A() 
    { 
     std::cout<<"~A()"<<std::endl; 
     delete a; 
    } 
}; 

struct B 
{ 
    A a; // if you remove this & you remove line 26 there wont be any call to A() 
    int b; 

    B() 
    { 
    // a = A(); // even if this line is removed there still a call to A() constructor 
     b = 10; 
    } 
}; 
void pause() // a simple pause function , that we let the system call before exiting to see the output 
{ 
    system("pause"); 
} 
int main() 
{ 
    atexit(pause); // to pause after calling all destructors 
    B * b = new B(); 
    delete b; 
    B * b1 = new B(); 
    delete b1; 
    return 0; 
} 
関連する問題