在<C++編程思想>2th中文版 第12.3.3.2節“返回值優化”中說,對于處理“return Integer(left.i + left.i);”這種的返回時,編譯器直接在目的內存中創建,且因為不是創建局部對象,故可直接調用普通構造函數,而不需要復制構造函數;但,對于
“
Integer temp;
return temp;
”
這樣的返回值形式,是需要調用復制構造函數來在目標內存中創建對象的。
我在VC2005中試了如下的小函數,
X f()
{
X one(5);
//return one; //因為VC中默認情況下debug模式優化被禁止;release模式優化可用,所以在release模式下直接將one的定義目標內存中;debug則是調用復制構造在目標內存中構造
//return X(4); // release & debug 都直接在目標內存中構造對象
}
int main()
{
X test = f();
}
對于,
Integer temp;
return temp;
這種形式,在VC2005中,如果沒有禁用優化,則不要求復制構造函數可訪問,也就是說復制構造函數都不會被調用。
但標準中說:“Even when the creation of the temporary object is avoided (12.8), all the semantic restrictions must be respected as if the temporary object was created. [ Example: even if the copy constructor is not called, all the semantic restrictions, such as accessibility (clause 11), shall be satisfied.]”,所以還是保留復制構造函數的可訪問性吧。
P.S. : 后來了解到VC中(或者說標準允許)對命名對象的返回采用“命名返回值優化(NRVO)”來進行優化,但是對于這種優化只有在某些編譯器選項開啟后才得以實現,至少VC是這樣的。
2009.6.18 更新
posted on 2009-05-24 23:11
zhaoyg 閱讀(975)
評論(0) 編輯 收藏 引用 所屬分類:
C/C++學習筆記