Copy constructor vs. return value optimization
-
21-08-2019 - |
Question
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 );
}
Solution
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"
OTHER TIPS
The standard says that the copy constructor need not be used - see section 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 perform a copy at all, even if the class copy constructor or destructor have side effects.
And much more in a similar vein.
Way not pass parameter by reference and assign result to it?
There's one very simple and good way to avoid such considerations completely - you can consider returning a boost::shared_ptr to the created object - it will be practically the same when it comes to usability but your object will surely not be copied unnecessarily - and it will be true also if you return it though a couple layers of function calls.