In the context of the C++ programming language, the return value optimization (RVO) is a compiler optimization that involves eliminating the temporary object created to hold a function's return value. The RVO is particularly notable for being allowed to change the observable behaviour of the resulting program by the C++ standard.
In general, the C++ standard allows a compiler to perform any optimization, provided the resulting executable exhibits the same observable behaviour as if (i.e. pretending) all the requirements of the standard have been fulfilled. This is commonly referred to as the "as-if rule". The term return value optimization refers to a special clause in the C++ standard that goes even further than the "as-if" rule: an implementation may omit a copy operation resulting from a return statement, even if the copy constructor has side effects.
The following example demonstrates a scenario where the implementation may eliminate one or both of the copies being made, even if the copy constructor has a visible side effect (printing text). The first copy that may be eliminated is the one where C()
is copied into the function f
's return value. The second copy that may be eliminated is the copy of the temporary object returned by f
to obj
.
Depending upon the compiler, and that compiler's settings, the resulting program may display any of the following outputs:
Returning an object of built-in type from a function usually carries little to no overhead, since the object typically fits in a CPU register. Returning a larger object of class type may require more expensive copying from one memory location to another. To avoid this, an implementation may create a hidden object in the caller's stack frame, and pass the address of this object to the function. The function's return value is then copied into the hidden object. Thus, code such as this: