函數返回類對象時,理論上會調用拷貝構造函數創建臨時對象再拷貝給調用者。但實測只調用一次構造函數,無拷貝構造輸出。
__result,在 return 前插入拷貝構造 __result.X::X(xx)。調用點轉為 X xx; func(xx);。仍有一次拷貝構造。__result 替換局部對象 xx,在 __result 上直接構造,省去拷貝。轉換後函數:void func(X& __result) { __result.X::X(); __result.setData(101); }。調用點不變。結果:零拷貝構造。
class X {
public:
X() { cout << "X::X()" << endl; }
X(const X&) { cout << "X::X(const X&)" << endl; }
void setData(int) {}
};
X func() { X xx; xx.setData(101); return xx; }
int main() { X xx = func(); return 0; }
// 輸出僅 "X::X()",NRV 優化生效