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.
First we shall verify that the operator-= is as efficient as we’d expect it to be:
(void)printf(“\nTry -= operator to test reference efficiency.\n”); Vector3 result1(vectB); result1 -= vectC; result1.print();
From the output this generates, we can deduce that we only need a constructor to construct ‘result1’ based on ‘vectB’ after which we only need to perform the subtraction to get our result. Apart from having to break a single statement into two separate ones, this looks like the perfect solution.
Try -= operator to test reference efficiency. ‘copy of vectB’ – Copy Constructed. ‘copy of vectB’ -= vectC finished. ‘copy of vectB’ at (-3.0 0.0 –3.0)
Next we can test the operator+. Notice that the difference between the operator+ and the operator- lies purely in the fact that the result is a local variable in the former and a constructor argument in the latter.
Still, this small difference has quite an impact on the code generated by the compiler. Luckily the compiler didn’t destroy the local result when it left the function's scope, otherwise we would have needed a temporary variable there. That would have brought an additional constructor and destructor call with it!
Try + operator to visualize temporary object. local result – Constructed. vectB + vectC finished. ‘copy of local result’ – Copy Constructed local result - Destructed. ‘copy of local result’ at (3.0 0.0 7.0)
And just by returning the result by value through a constructor argument, we (or better yet the compiler) discover we are as efficient with the operator- as we are with the operator-= …
(void)printf(“\nTry – operator for return value optimization.\n”); Vector3 result3(vectB – vectC); result3.print();
Again we only need a constructor and the subtraction operations to come to our result. The difference here is that the subtraction is actually performed and finished before the construction of the final result –- which happens to have become the constructor argument itself. Very ingenious and efficient as well!
Try – operator for return value optimization. VectB – vectC finished. ctor arg – Constructed. ctor arg at (-3.0 0.0 –3.0)
Nowadays compilers are becoming more complex, and it might be possible for them to discover that it is safe to apply ‘Return Value Optimization’ to your functions. It doesn’t hurt to give them a helping hand though; you’ve now seen the difference it can make.