2017-06-28 29 views
2

我在析構函數上做過實踐,但編譯這個程序時我不知道爲什麼輸出不如我想的那樣。析構函數如何執行?

#include <iostream> 
using namespace std; 
class aaa 
{ 
    private: 
    static int x; 
    int code; 
    public: 
    /*after constructor executes 3 times the value of "code" becomes 103*/ 
    aaa() 
    { 
    code=x; 
    cout<<"Default Constructor"<<endl; 
    x++; 
    } 
    ~aaa() 
    { 
    cout<<"Destructor of "<<code<<endl; 
    } 
}; 
int aaa::x=101; 
int main() 
{ 
    aaa *p; 
    p=new aaa[3]; 
    delete []p; 
    return 0; 
} 

輸出是:

Default Constructor 
Default Constructor 
Default Constructor 
Destructor of 103 
Destructor of 102 
Destructor of 101 

,而我認爲這將是這樣的:

101 
102 
103 

回答

1

我不知道爲什麼輸出不如我想象的那樣。

因爲物件按照構造的相反順序被破壞:首先構造,最後被破壞。

構造函數調用的逆向排序中調用了析構函數,這解釋了您所看到的行爲。

因此,當您爲數組動態分配內存new[]時,構造函數會按自然順序(您所期望的)調用,但當調用delete[]釋放該內存時,數組中的每個元素都會被破壞相反的順序。

詳情請閱讀Why destructors are not called in reverse order for array of objects?


如果我寫delete p代替delete []p會發生什麼,所以浩多次調用析構函數?

C++要求您刪除delete[]的數組,並使用delete刪除非數組。所以我無法回答。詳情請閱讀Delete and delete [] are the same when deleting arrays?

+0

以及如果我寫delete p而不是delete [] p會發生什麼,因此很多時候Destructor是叫 –

+0

@AmanWarudkar https://stackoverflow.com/questions/6953457/delete-and-delete-are-the-same-when-deleting-arrays – Curious

+1

@AmanWarudkar更新了我的答案,希望這有助於!不要忘記*接受*答案。好奇的感謝鏈接和很好的答案順便說一句。 – gsamaras

3

破壞發生在施工的相反順序,這就是爲什麼你看到的析構函數爲103首先叫。

即當您分配數組時,new[]構造一個方向的對象,然後當您調用delete[]時,對象將從數組末尾被銷燬。關於此行爲,請參閱@StoryTeller's answer for a quote from the C++ standard

+0

,如果我寫,刪除p,而不是刪除[] P,所以浩多次調用析構函數 –

+0

@AmanWarudkar看看會發生什麼https://stackoverflow.com/questions/6953457/delete-and-delete-are -the-same-when-deletion-arrays應該總是刪除用'new []'分配的數組'delete []' – Curious

2

析構函數被調用以相反的順序對象初始化,並通過delete[]破壞以及數組是正確的:

[expr.delete/6]

如果刪除的操作數的值-expression不是NULL指針值,則delete-expression將調用析構函數(如果有 任何),該對象或要刪除的數組的元素。 在 數組的情況下,元素將按照 遞減地址的順序銷燬(即按照完成 的構造函數;請參見[class.base.init])的相反順序。

+1

打敗我的標準報價! – Curious