C++ – Copy Constructor vs. Return Value Optimization

c++copy-constructorreturn-value-optimization

In a previous question, it appeared that a plain return-by-value function always copies its return argument into the variable being assigned from it.

Is this required by the standard, or can the function be optimized by constructing the 'assigned to' variable even within the function body?

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 ); 
}

Best Answer

The standard allows any level of copy omission here:

  • construct a local temporary, copy-construct it into a return value, and copy-construct the return value into the local "c". OR
  • construct a local temporary, and copy-construct that into "c". OR
  • construct "c" with the arguments "i,d"
Related Question