2012-01-04 88 views
2

可能重複:
Understanding return value optimization and returning temporaries - C++步驟返回值優化

Integer是一些類i,因爲它的成員。 leftright作爲參數傳遞給函數調用,並且類型爲Integer

現在在Bruce Eckel中給出。

代碼1:

return Integer(left.i+right.i); 

代碼2:

Integer tmp(left.i+right.i); 
return tmp; 

碼1說做一個臨時的整數對象並返回它,它是從創建一個名爲局部變量和返回它,不同的這是一個普遍的誤解。

在代碼1(稱爲返回一個臨時的辦法):
編譯器知道你有沒有其他需要它的創建,然後返回後援編譯器building the object directly into the location of the outside return value利用了這一目標。這個只需要一個普通的構造函數調用(沒有拷貝構造函數)和沒有本地對象沒有創建析構函數是必需的。

雖然3個事物代碼2會發生:
一個)TMP對象被創建,包括它的構造呼叫
b)中the copy-constructor copies the tmp to the location of the outside return value
c)中析構函數被調用,用於在範圍結束TMP。

在代碼1這是什麼意思:building the object directly into the location of the outside return value
也爲什麼複製構造函數不會在代碼1中調用?

另外我不明白代碼2中的步驟b在做什麼?即the copy-constructor copies the tmp to the location of the outside return value

+0

'Integer'屬於Java。 – iammilind 2012-01-04 08:25:08

+0

假設它是在這裏定義的(代碼未顯示),它有一個int成員我和其餘函數。 – 2012-01-04 08:26:32

+2

一個好的編譯器會爲這兩種情況創建相同的彙編代碼。 – littleadv 2012-01-04 08:27:16

回答

2

編譯器可自由優化複製構造函數傳遞值返回值。我的猜測是,任何像樣的優化將產生的這兩種方式相同的二進制。

代碼的優化版本:

A foo() 
{ 
    A temp; 
00401000 mov   ecx,dword ptr [A::x (40337Ch)] 
00401006 mov   dword ptr [eax],ecx 
00401008 add   ecx,1 
0040100B mov   dword ptr [A::x (40337Ch)],ecx 
    return temp; 
} 

所以你看,拷貝構造函數不叫,即使在我的版本,它有一個cout,所以它確實會影響觀察到的行爲。

沒有優化:

A foo() 
{ 
004113C0 push  ebp 
004113C1 mov   ebp,esp 
004113C3 sub   esp,0CCh 
004113C9 push  ebx 
004113CA push  esi 
004113CB push  edi 
004113CC lea   edi,[ebp-0CCh] 
004113D2 mov   ecx,33h 
004113D7 mov   eax,0CCCCCCCCh 
004113DC rep stos dword ptr es:[edi] 
    A temp; 
004113DE lea   ecx,[temp] 
004113E1 call  A::A (4110E6h) 
    return temp; 
004113E6 lea   eax,[temp] 
004113E9 push  eax 
004113EA mov   ecx,dword ptr [ebp+8] 

/// copy constructor called on next line: 

004113ED call  A::A (411177h) 
004113F2 mov   eax,dword ptr [ebp+8] 
} 

短語「B)拷貝構造函數複製tmp目錄外返回值的位置。」是遠feched,有時甚至不發生。

你應該記住的是,你不應該依賴被調用的拷貝構造函數。

+0

完美合理的答案,不知道爲什麼它是downvoted。 – littleadv 2012-01-04 08:34:50

+0

@littleadv它可能沒有完全回答這個問題。無論如何,我編輯的時候要更具說明性。 – 2012-01-04 08:39:22