C++深度解析(13)—局部、全局、堆對象的構造順序

1.問題

  • C++中的類可以定義多個對象, 那麼對象構造的順序是怎樣的?
    • 局部對象的構造順序依賴於程序的執行流 
    • 堆對象的構造順序依賴於new的使用順序 
    • 全局對象的構造順序是不確定的 

1.1 局部對象的構造順序

  • 對於局部對象:當程序執行流到達對象的定義語句時進行構造 
  1. #include <stdio.h>
  2. class Test
  3. {
  4. private:
  5. int mi;
  6. public:
  7. Test(int i)
  8. {
  9. mi = i;
  10. printf("Test(int i): %d\n", mi);
  11. }
  12. Test(const Test &obj)
  13. {
  14. mi = obj.mi;
  15. printf("Test(const Test &obj): %d\n", mi);
  16. }
  17. };
  18. int main()
  19. {
  20. int i = 0;
  21. Test a1 = i;
  22. while (i < 3)
  23. {
  24. Test a2 = ++i;
  25. }
  26. if (i < 4 )
  27. {
  28. Test a = a1; // 調用拷貝構造函數
  29. }
  30. else
  31. {
  32. Test a(100);
  33. }
  34. getchar();
  35. return 0;
  36. }
  • 運行結果:

1.2 堆對象的構造順序

  • 對於堆對象 
    • 當程序執行流到達new語句時創建對象 
    • 使用new創建對象將自動觸發構造函數的調用
  1. #include <stdio.h>
  2. class Test
  3. {
  4. private:
  5. int mi;
  6. public:
  7. Test(int i)
  8. {
  9. mi = i;
  10. printf("Test(int i): %d\n", mi);
  11. }
  12. Test(const Test &obj)
  13. {
  14. mi = obj.mi;
  15. printf("Test(const Test &obj): %d\n", mi);
  16. }
  17. };
  18. int main()
  19. {
  20. int i = 0;
  21. Test * a1 = new Test(i); // Test(int i): 0
  22. while (++i < 10) // Test(int i):1,3,5,7,9
  23. {
  24. if (i % 2)
  25. new Test(i);
  26. }
  27. if ( i < 4 )
  28. new Test(*a1);
  29. else
  30. new Test(100); // Test(int i): 100
  31. getchar();
  32. return 0;
  33. }
  • 運行結果:

1.3 全局對象的構造

  • 對於全局對象 
    •  對象的構造順序是不確定的 
    • 不同的編譯器使用不同的規則確定構造順序 
  • test.h
  1. #ifndef _TEST_H_  
  2. #define _TEST_H_  
  3.   
  4. #include <stdio.h>  
  5.   
  6. class Test  
  7. {  
  8. public:  
  9.     Test(const char *s)  
  10.     {  
  11.         printf("%s\n", s);  
  12.     }  
  13. };  
  14.   
  15. #endif  
  • test.cpp
  1. #include "test.h"  
  2.   
  3. Test t4("t4");  
  4.   
  5. int main()  
  6. {  
  7.     Test t5("t5");  
  8. }  
  • t1.cpp
  1. #include "test.h"  
  2.   
  3. Test t1("t1");  
  • t2.cpp
  1. #include "test.h"  
  2.   
  3. Test t2("t2");  
  • t3.cpp
  1. #include "test.h"  
  2.   
  3. Test t3("t3")
  • 不同編譯器執行結果

2.小結

  • 局部對象的構造順序依賴於程序的執行流 
  • 堆對象的構造順序依賴於new的使用順序 
  • 全局對象的構造順序是不確定的           
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章