1.問題
- C++中的類可以定義多個對象, 那麼對象構造的順序是怎樣的?
- 局部對象的構造順序依賴於程序的執行流
- 堆對象的構造順序依賴於new的使用順序
- 全局對象的構造順序是不確定的
1.1 局部對象的構造順序
- 對於局部對象:當程序執行流到達對象的定義語句時進行構造
- #include <stdio.h>
-
- class Test
- {
- private:
- int mi;
-
- public:
-
- Test(int i)
- {
- mi = i;
- printf("Test(int i): %d\n", mi);
- }
-
- Test(const Test &obj)
- {
- mi = obj.mi;
- printf("Test(const Test &obj): %d\n", mi);
- }
- };
-
- int main()
- {
- int i = 0;
- Test a1 = i;
-
- while (i < 3)
- {
- Test a2 = ++i;
- }
-
- if (i < 4 )
- {
- Test a = a1; // 調用拷貝構造函數
- }
- else
- {
- Test a(100);
- }
-
- getchar();
-
- return 0;
- }
- 運行結果:
1.2 堆對象的構造順序
- 對於堆對象
- 當程序執行流到達new語句時創建對象
- 使用new創建對象將自動觸發構造函數的調用
- #include <stdio.h>
-
- class Test
- {
- private:
- int mi;
-
- public:
-
- Test(int i)
- {
- mi = i;
- printf("Test(int i): %d\n", mi);
- }
-
- Test(const Test &obj)
- {
- mi = obj.mi;
- printf("Test(const Test &obj): %d\n", mi);
- }
- };
-
-
- int main()
- {
- int i = 0;
- Test * a1 = new Test(i); // Test(int i): 0
-
- while (++i < 10) // Test(int i):1,3,5,7,9
- {
- if (i % 2)
- new Test(i);
- }
- if ( i < 4 )
- new Test(*a1);
- else
- new Test(100); // Test(int i): 100
-
- getchar();
-
- return 0;
- }
- 運行結果:
1.3 全局對象的構造
- 對於全局對象
- 對象的構造順序是不確定的
- 不同的編譯器使用不同的規則確定構造順序
- test.h
- #ifndef _TEST_H_
- #define _TEST_H_
-
- #include <stdio.h>
-
- class Test
- {
- public:
- Test(const char *s)
- {
- printf("%s\n", s);
- }
- };
-
- #endif
- test.cpp
- #include "test.h"
-
- Test t4("t4");
-
- int main()
- {
- Test t5("t5");
- }
- t1.cpp
- #include "test.h"
-
- Test t1("t1");
- t2.cpp
- #include "test.h"
-
- Test t2("t2");
- t3.cpp
- #include "test.h"
-
- Test t3("t3");
- 不同編譯器執行結果
2.小結
- 局部對象的構造順序依賴於程序的執行流
- 堆對象的構造順序依賴於new的使用順序
- 全局對象的構造順序是不確定的