[英]Copy constructor vs. return value optimization
在上一個問題中,似乎一個普通的按值返回 function 總是將其return
參數復制到從中分配的變量中。
這是標准要求的,還是可以通過在 function 體內構造“分配給”變量來優化 function?
struct C { int i; double d; };
C f( int i, int d ) {
return C(i,d); // construct _and_ copy-construct?
}
int main() {
C c = f( 1, 2 );
}
該標准允許在此處進行任何級別的復制遺漏:
該標准說不需要使用復制構造函數 - 請參閱第 12.8/15 節:
15 Whenever a temporary class object is copied using a copy constructor, and this object and the copy have the same cv-unqualified type, an implementation is permitted to treat the original and the copy as two different ways of referring to the same object and not完全執行復制,即使 class 復制構造函數或析構函數有副作用。
還有更多類似的情況。
方式不通過引用傳遞參數並將結果分配給它?
有一種非常簡單且很好的方法可以完全避免此類考慮 - 您可以考慮將 boost::shared_ptr 返回到創建的 object - 在可用性方面實際上是相同的,但您的 object 肯定不會被不必要地復制 - 而且它如果您通過幾層 function 調用返回它,這也是正確的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.