在 C++ 中的類能夠定義多個對象,那麼對象構造的順序是怎樣的呢?對於局部對象:當程序執行流到達對象的定義語句時進行構造。咱們以代碼爲例進行分析ide
#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; // Test(int i): 0 while( i < 3 ) { Test a2 = ++i; // Test(int i): 1, 2, 3 } if( i < 4 ) { Test a = a1; // Test(const Test& obj): 0 } else { Test a(100); } return 0; }
咱們按照程序的執行流能夠看到先是執行對象 a1 的建立,接着是對象 a2 的建立 3 次,最後是對象 a 的拷貝構造。咱們看看結果是否如咱們所分析的那樣函數
咱們看到局部對象的構造順序確實如咱們所想的那樣。若是咱們使用 goto 語句呢,咱們看個代碼學習
#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 getMI() { return mi; } }; int main() { int i = 0; Test a1 = i; // Test(int i): 0 while( i < 3 ) { Test a2 = ++i; // Test(int i): 1, 2, 3 } goto End; Test a(100); End: printf("a.mi = %d\n", a.getMI()); return 0; }
咱們來編譯看看優化
編譯直接出錯,由於咱們使用了 goto 語句,致使程序的執行流出錯了。
spa
接下來咱們來看看堆對象的構造順序,當程序執行流到達 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 getMI() { return mi; } }; int main() { int i = 0; Test* a1 = new Test(i); // Test(int i): 0 while( ++i < 10 ) if( i % 2 ) new Test(i); // Test(int i): 1, 3, 5, 7, 9 if( i < 4 ) new Test(*a1); else new Test(100); // Test(int i): 100 return 0; }
咱們看看是否如咱們所註釋的那樣執行的圖片
確實,堆對象的構造順序是跟 new 關鍵字有關係的。下來咱們來看看全局對象,對象的構造順序是不肯定的,不一樣的編譯器使用不一樣的規則來肯定構造順序。仍是以代碼爲例來進行驗證get
test.h 源碼
編譯器
#ifndef _TEST_H_ #define _TEST_H_ #include <stdio.h> class Test { public: Test(const char* s) { printf("%s\n", s); } }; #endif
t1.cpp 源碼
#include "test.h" Test t1("t1");
t2.cpp 源碼
#include "test.h" Test t2("t2");
t3.cpp 源碼
#include "test.h" Test t3("t3");
test.cpp 源碼
#include "test.h" Test t4("t4"); int main() { Test t5("t5"); return 0; }
咱們來編譯看看結果
這個結果貌似跟咱們指定編譯的順序有關係,咱們再來看看BCC編譯器呢
再來試試 VS2010
之前博主在書上和視頻中看到過全局對象的構造順序是不肯定的,可能如今的編譯器作了優化吧。反正咱們記住就能夠了,儘可能避免使用全局對象。經過對對象的構造順序的學習,總稽覈以下:局部對象的構造順序依賴於程序的執行流;堆對象的構造順序依賴於 new 的使用順序;全局對象的構造順序是不肯定的
歡迎你們一塊兒來學習 C++ 語言,能夠加我QQ:243343083。