2013-04-21 73 views
0

實施例:析構函數如何去除嵌套的堆棧類型?

class A 
{ 
    char * data; 
    ... 
    A(){data = new char[50];} 
    ~A(){delete [] data;} 
}; 

class B 
{ 
    A a; 

    B(); 
    // default destructor 
} 

void foo() 
{ 
    B b; 
} 

int main() 
{ 
    foo(); 

    // "A.data" still in the heap or no? 
} 

該程序被正確和「A.data」將在主FOO()之後去除,或將在堆中還存在嗎?

+0

對不起,修正。問題依然存在。 – 2013-04-21 21:19:22

回答

5

是的,它會被刪除,通過你需要使用delete[]陣列。你還應該記住Rule of three

+0

或者使用'std :: vector'跳舞到[Rule of Zero](http://isocpp.org/blog/2012/11/rule-of-zero) – 2013-04-21 21:51:52

3
~A(){delete data;} 

應該

~A() 
{ 
    delete[] data; 
} 
//remove the dynamic array 

在當前的代碼中,當主退出時,它會調用析構函數來釋放內存和堆將不存在。

2

當一個對象被破壞時,編譯器自動破壞所有類的非指針數據成員。因此,當B b變量超出範圍時,編譯器自動破壞它,然後破壞A a數據成員,因爲它不是指針,它會調用~A()來釋放數組。

+0

非常感謝! – 2013-04-21 21:40:19