There are situations in C++ when it is good to return the result of a function by value rather than by reference. There is usually a price to be paid, however...unless the compiler can be made to help. Jun Nakamura explains.
Temporary Variables: Chasing Temporaries Away - Return Value Optimization (Page 2 of 5 )
The official term for what we are aiming to achieve is ‘Return Value Optimization.’ This is a technique where you tell the compiler that it is safe to kill the temporary object needed for the returned value.
All you need to do is return a constructor argument and the compiler will take care of the rest. When an object is created directly inside a statement, without being assigned to a variable, we are looking at a constructor argument.
Lets build a sample portion of the Vector3 class as I did in the first article to visualize the compiler’s actions. We’ll implement the -= operator, the + operator and the - operator. The -= operator will demonstrate the efficiency of references, the + operator will show what happens when we don’t facilitate for return value optimization and the – operator will show the effect of return value optimization.
You can see that operator+ uses a local variable, which is then returned by value, while the operator- uses what we now recognize as a constructor argument. We expect operator-= to be nothing less than the most efficient… but what better way than to verify this by running some code?
Note that normally it is recommended that you use std::string instead of char buffers. Here I thought it would keep the class a bit more compact, and sometimes it is just easier to use printf and sprintf instead of STL streams. Please don’t send me any emails about possible buffer overflows, as this is simply sample code. ;)