在 C++ 中的類可以定義多個對象,那么對象構造的順序是怎樣的呢?對于局部對象:當程序執行流到達對象的定義語句時進行構造。我們以代碼為例進行分析

#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 語句,導致程序的執行流出錯了。
接下來我們來看看堆對象的構造順序,當程序執行流到達 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 關鍵字有關系的。下來我們來看看全局對象,對象的構造順序是不確定的,不同的編譯器使用不同的規則來確定構造順序。還是以代碼為例來進行驗證
test.h 源碼
#ifndef _TEST_H_
#define _TEST_H_
#include <stdio.h>
class Test
{
public:
Test(const char* s)
{
printf("%s\n", s);
}
};
#endift1.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。
另外有需要云服務器可以了解下創新互聯scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業上云的綜合解決方案,具有“安全穩定、簡單易用、服務可用性高、性價比高”等特點與優勢,專為企業上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。
網站名稱:對象的構造順序(十六)-創新互聯
轉載源于:http://www.yijiale78.com/article6/docdig.html
成都網站建設公司_創新互聯,為您提供企業建站、微信公眾號、網站設計、虛擬主機、網頁設計公司、外貿網站建設
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯