在<C++編程思想>2th中文版 第12.3.3.2節(jié)“返回值優(yōu)化”中說,對于處理“return Integer(left.i + left.i);”這種的返回時,編譯器直接在目的內(nèi)存中創(chuàng)建,且因為不是創(chuàng)建局部對象,故可直接調(diào)用普通構(gòu)造函數(shù),而不需要復(fù)制構(gòu)造函數(shù);但,對于
“
Integer temp;
return temp;
”
這樣的返回值形式,是需要調(diào)用復(fù)制構(gòu)造函數(shù)來在目標內(nèi)存中創(chuàng)建對象的。
我在VC2005中試了如下的小函數(shù),
X f()
{
X one(5);
//return one; //因為VC中默認情況下debug模式優(yōu)化被禁止;release模式優(yōu)化可用,所以在release模式下直接將one的定義目標內(nèi)存中;debug則是調(diào)用復(fù)制構(gòu)造在目標內(nèi)存中構(gòu)造
//return X(4); // release & debug 都直接在目標內(nèi)存中構(gòu)造對象
}
int main()
{
X test = f();
}
對于,
Integer temp;
return temp;
這種形式,在VC2005中,如果沒有禁用優(yōu)化,則不要求復(fù)制構(gòu)造函數(shù)可訪問,也就是說復(fù)制構(gòu)造函數(shù)都不會被調(diào)用。
但標準中說:“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.]”,所以還是保留復(fù)制構(gòu)造函數(shù)的可訪問性吧。
P.S. : 后來了解到VC中(或者說標準允許)對命名對象的返回采用“命名返回值優(yōu)化(NRVO)”來進行優(yōu)化,但是對于這種優(yōu)化只有在某些編譯器選項開啟后才得以實現(xiàn),至少VC是這樣的。
2009.6.18 更新
posted on 2009-05-24 23:11
zhaoyg 閱讀(970)
評論(0) 編輯 收藏 引用 所屬分類:
C/C++學(xué)習(xí)筆記