2015-07-06 64 views
0

析構函數按照與C++中對象創建相反的順序調用,但我不明白爲什麼它沒有爲對象數組維護。爲什麼析構函數不按相反順序調用對象數組?

#include <iostream> 
using namespace std; 
class test { 
    int nmbr; 
    static int c; 
public: 
    test(int j) 
    { 
     cout<<"constructor is called for object no :"<<j<<endl; 
     nmbr=j; 
    }; 
    ~test() 
    { 
     c++; 
     cout<<"destructor is called for object no :"<<c<<endl; 
    }; 
}; 

int test::c=0; 

int main() 
{ 
    test ob[]={test(1),test(2),test(3)}; 
    return 0; 
} 

上述程序輸出

constructor is called for object no :1 
constructor is called for object no :2 
constructor is called for object no :3 
destructor is called for object no :1 
destructor is called for object no :2 
destructor is called for object no :3 

但爲什麼析構函數不按相反的順序叫什麼?

+3

嘗試'測試ob [] = {測試(97),測試(1043),測試(-12)};'看看會發生什麼。 – molbdnilo

+0

或設置test :: c = 5或0以外的任意隨機數。你會明白 –

回答

6

它以相反的順序調用。您正在打印變量c。看看我在這個程序中的評論 - 「我在這裏改變了」。您正在打印一個計數變量,您應該已經打印了正在銷燬的對象。

你可以在這裏閱讀更多: https://isocpp.org/wiki/faq/dtors#order-dtors-for-arrays

#include <iostream> 
using namespace std; 
class test { 
    int nmbr; 
    static int c; 
public: 
    test(int j) 
    { 
     cout<<"constructor is called for object no :"<<j<<endl; 
     nmbr=j; 
    }; 
    ~test() 
    { 
     c++; 
     // I changed here 
     cout<<"destructor is called for object no :"<<nmbr<<endl; 
    }; 
}; 

int test::c=0; 

int main() 
{ 
    test ob[]={test(1),test(2),test(3)}; 
    return 0; 
} 
+0

愚蠢的錯誤。謝謝,現在我應該刪除這篇文章,因爲這個問題將來有助於任何人的可能性很小? –

2

它們是,錯誤的是與你的測試。在調用析構函數時,您正在訪問您正在設置的一個數字。更改析構函數輸出到顯示類中的實際價值,你會看到自己

cout<<"destructor is called for object no :"<<nmbr<<endl; 
+0

你剛剛複製了其他答案的代碼? –

+1

不會,在同一時間寫作,發生。看不出有什麼理由爲此付出代價 – Modred

1

的析構函數中調用構造函數調用的順序相反。

這是您的測試是錯誤地生成和打印值。

試試看這個代碼,你會看到預期的結果。

#include <iostream> 

class test { 
    int this_instance; 
    static int number_of_instances; 
public: 
    test() : this_instance(number_of_instances++) 
    { 
     std::cout << "constructor invoked for object :"<< this_instance << '\n'; 
    }; 
    ~test() 
    { 
     std::cout << "destructor invoked for object :" << this_instance << '\n'; 
    }; 
}; 

int test::number_of_instances = 0; 

int main() 
{ 
    test first_batch[4]; 

    return 0; 
} 
相關問題