[C++]對象的銷毀機制


銷毀時會按照從后向前的順序銷毀,也就是說,越在后面定義的對象會越早銷毀。其中的原因就是函數是在棧中保存的,因此,先定義的對象先壓棧,所以在退棧時就會后銷毀。而如果參數有多個的話,大多數編譯器是從右開始壓棧的,也就是參數列表最右邊的變量最先壓棧,所以參數列表最右邊的變量會在最后銷毀。

代碼如下:

 1 #include<iostream>
 2 
 3 using namespace std;
 4 
 5 class Matter {
 6 public:
 7     Matter(int id) : _identifier(id) 
 8         {cout << "Matter from " << _identifier << endl; }
 9     ~Matter()
10         { cout << "Matter Bye from " << _identifier << endl; }
11 
12 private:
13     const int _identifier;
14 };
15 
16 class World {
17 public:
18     World(int id) : _identifier(id),_matter(id)
19         {cout << "Hello from " << _identifier << endl; }
20     ~World() { cout << "Bye from " << _identifier << endl; }
21 
22 private:
23     const int _identifier;
24     Matter _matter;
25 };
26 
27 World TheWorld(1);
28 
29 int main() {
30     World smallWorld(2);
31     cout << "hello from main()\n";
32     World oneMoreWorld(3);
33 
34     return 0;
35 }

輸出結果

Matter from 1 
Hello from 1
Matter from 2 
Hello from 2 
Hello from main()
Matter from 3 
Hello from 3
Bye from 3
Matter Bye from 3
Bye from 2
Matter Bye from 2
Bye from 1
Matter Bye from 1

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM