Take use of the return value optimization in compilers.
Some functions (such as operator*
) have to return objects:
- if returning pointers, the caller is responsible to delete the pointer, which usually leads to resource leaks.
- if returning references, then we’re returning a reference to a local object, which no longer exists when the caller has it.
Although we can’t eliminate by-value returns from functions that require them, we can still reduce the cost of returning objects: by the help of compilers, we can eliminate the cost of the temporaries by returning constructor arguments instead of objects:
|
|
Here we’re creating an anonymous temporary Rational
object through a constructor expression, ant it is this temporary object the function is copying for its return value. When we use this efficient version of operator*
under the use case below:
|
|
The rules for C++ allow compilers to optimize such anonymous temporary objects out of existence by constructing the temporary inside the memory allotted for the object c
. Thus, if compilers do this optimization, both the temporary inside operator*
and the temporary returned by operator*
are eliminated, and we only pay for one constructor call - the one to create c
.
Further more, we can eliminate the overhead of the call to operator*
by declaring this function inline
:
|
|