可能重複:
Understanding return value optimization and returning temporaries - C++步驟返回值優化
讓Integer
是一些類i
,因爲它的成員。 left
和right
作爲參數傳遞給函數調用,並且類型爲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
。
'Integer'屬於Java。 – iammilind 2012-01-04 08:25:08
假設它是在這裏定義的(代碼未顯示),它有一個int成員我和其餘函數。 – 2012-01-04 08:26:32
一個好的編譯器會爲這兩種情況創建相同的彙編代碼。 – littleadv 2012-01-04 08:27:16