Return Value Optimization
   HOME

TheInfoList



OR:

In
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
computer programming Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as ana ...
, copy elision refers to a
compiler optimization In computing, an optimizing compiler is a compiler that tries to minimize or maximize some attributes of an executable computer program. Common requirements are to minimize a program's execution time, memory footprint, storage size, and power con ...
technique that eliminates unnecessary copying of objects. The C++ language standard generally allows implementations to perform any optimization, provided the resulting program's observable behavior is the same '' as if'', i.e. pretending, the program were executed exactly as mandated by the standard. Beyond that, the standard also describes a few situations where copying can be eliminated even if this would alter the program's behavior, the most common being the return value optimization (see below). Another widely implemented optimization, described in the
C++ standard C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
, is when a temporary object of class type is copied to an object of the same type.
ISO ISO is the most common abbreviation for the International Organization for Standardization. ISO or Iso may also refer to: Business and finance * Iso (supermarket), a chain of Danish supermarkets incorporated into the SuperBest chain in 2007 * Iso ...
/
IEC The International Electrotechnical Commission (IEC; in French: ''Commission électrotechnique internationale'') is an international standards organization that prepares and publishes international standards for all electrical, electronic and r ...
(2003). '' ISO/IEC 14882:2003(E): Programming Languages - C++ §12.8 Copying class objects lass.copy' para. 15
As a result, ''copy-initialization'' is usually equivalent to ''direct-initialization'' in terms of performance, but not in semantics; ''copy-initialization'' still requires an
accessible Accessibility is the design of products, devices, services, vehicles, or environments so as to be usable by people with disabilities. The concept of accessible design and practice of accessible development ensures both "direct access" (i. ...
copy constructor In class-based, object-oriented programming, a constructor (abbreviation: ctor) is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required ...
. The optimization can not be applied to a temporary object that has been bound to a reference.


Example

#include int n = 0; struct C ; // it modifies an object with static storage duration int main() According to the standard a similar optimization may be applied to objects being thrown and caught,
ISO ISO is the most common abbreviation for the International Organization for Standardization. ISO or Iso may also refer to: Business and finance * Iso (supermarket), a chain of Danish supermarkets incorporated into the SuperBest chain in 2007 * Iso ...
/
IEC The International Electrotechnical Commission (IEC; in French: ''Commission électrotechnique internationale'') is an international standards organization that prepares and publishes international standards for all electrical, electronic and r ...
(2003). '' ISO/IEC 14882:2003(E): Programming Languages - C++ §15.1 Throwing an exception xcept.throw' para. 5
ISO ISO is the most common abbreviation for the International Organization for Standardization. ISO or Iso may also refer to: Business and finance * Iso (supermarket), a chain of Danish supermarkets incorporated into the SuperBest chain in 2007 * Iso ...
/
IEC The International Electrotechnical Commission (IEC; in French: ''Commission électrotechnique internationale'') is an international standards organization that prepares and publishes international standards for all electrical, electronic and r ...
(2003). '' ISO/IEC 14882:2003(E): Programming Languages - C++ §15.3 Handling an exception xcept.handle' para. 17
but it is unclear whether the optimization applies to both the copy from the thrown object to the ''exception object'', and the copy from the ''exception object'' to the object declared in the ''exception-declaration'' of the ''catch clause''. It is also unclear whether this optimization only applies to temporary objects, or named objects as well. Given the following source code: #include struct C ; void f() // It is unclear whether this copy may be elided (omitted). int main() A conforming
compiler In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs that ...
should therefore produce a
program Program, programme, programmer, or programming may refer to: Business and management * Program management, the process of managing several related projects * Time management * Program, a part of planning Arts and entertainment Audio * Progra ...
which prints "Hello World!" twice. In the current revision of the C++ standard (
C++11 C++11 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions by ...
), the issues have been addressed, essentially allowing both the copy from the named object to the exception object, and the copy into the object declared in the exception handler to be elided. GCC provides the -fno-elide-constructors option to disable copy-elision. This option is useful to observe (or not observe) the effects of return value optimization or other optimizations where copies are elided. It is generally not recommended to disable this important optimization.


Return value optimization

In the context of the
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
, return value optimization (RVO) is a
compiler optimization In computing, an optimizing compiler is a compiler that tries to minimize or maximize some attributes of an executable computer program. Common requirements are to minimize a program's execution time, memory footprint, storage size, and power con ...
that involves eliminating the temporary object created to hold a
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-oriente ...
's return value. RVO is allowed to change the observable behaviour of the resulting
program Program, programme, programmer, or programming may refer to: Business and management * Program management, the process of managing several related projects * Time management * Program, a part of planning Arts and entertainment Audio * Progra ...
by the
C++ standard C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
.


Summary

In general, the C++ standard allows a
compiler In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs that ...
to perform any optimization, provided the resulting
executable In computing, executable code, an executable file, or an executable program, sometimes simply referred to as an executable or binary, causes a computer "to perform indicated tasks according to encoded instruction (computer science), instructi ...
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".
ISO ISO is the most common abbreviation for the International Organization for Standardization. ISO or Iso may also refer to: Business and finance * Iso (supermarket), a chain of Danish supermarkets incorporated into the SuperBest chain in 2007 * Iso ...
/
IEC The International Electrotechnical Commission (IEC; in French: ''Commission électrotechnique internationale'') is an international standards organization that prepares and publishes international standards for all electrical, electronic and r ...
(2003). '' ISO/IEC 14882:2003(E): Programming Languages - C++ §1.9 Program execution ntro.execution' para. 1
The term ''return value optimization'' refers to a special clause in the
C++ standard C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
that goes even further than the "as-if" rule: an implementation may omit a copy operation resulting from a
return statement In computer programming, a return statement causes execution to leave the current subroutine and resume at the point in the code immediately after the instruction which called the subroutine, known as its return address. The return address is sav ...
, even if the
copy constructor In class-based, object-oriented programming, a constructor (abbreviation: ctor) is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required ...
has
side effects In medicine, a side effect is an effect, whether therapeutic or adverse, that is secondary to the one intended; although the term is predominantly employed to describe adverse effects, it can also apply to beneficial, but unintended, consequence ...
.
ISO ISO is the most common abbreviation for the International Organization for Standardization. ISO or Iso may also refer to: Business and finance * Iso (supermarket), a chain of Danish supermarkets incorporated into the SuperBest chain in 2007 * Iso ...
/
IEC The International Electrotechnical Commission (IEC; in French: ''Commission électrotechnique internationale'') is an international standards organization that prepares and publishes international standards for all electrical, electronic and r ...
(2003). '' ISO/IEC 14882:2003(E): Programming Languages - C++ §12.8 Copying class objects lass.copy' para. 15
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 a nameless temporary C could be copied into the function f's
return value In computer programming, a return statement causes execution to leave the current subroutine and resume at the point in the code immediately after the instruction which called the subroutine, known as its return address. The return address is sa ...
. The second copy that may be eliminated is the copy of the temporary object returned by f to obj. #include struct C ; C f() int main() Depending upon the
compiler In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs that ...
, and that compiler's settings, the resulting
program Program, programme, programmer, or programming may refer to: Business and management * Program management, the process of managing several related projects * Time management * Program, a part of planning Arts and entertainment Audio * Progra ...
may display any of the following outputs:
Hello World!
A copy was made.
A copy was made.
Hello World!
A copy was made.
Hello World!


Background

Returning an object of
built-in type In computer science, primitive data types are a set of basic data types from which all other data types are constructed. Specifically it often refers to the limited set of data representations in use by a particular processor, which all compiled pr ...
from a
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-oriente ...
usually carries little to no overhead, since the object typically fits in a
CPU register A processor register is a quickly accessible location available to a computer's processor. Registers usually consist of a small amount of fast storage, although some registers have specific hardware functions, and may be read-only or write-only. ...
. 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 In computer science, a call stack is a stack data structure that stores information about the active subroutines of a computer program. This kind of stack is also known as an execution stack, program stack, control stack, run-time stack, or mac ...
, 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: struct Data ; Data F() int main() may generate code equivalent to this: struct Data ; Data* F(Data* _hiddenAddress) int main() which causes the Data object to be copied twice. In the early stages of the evolution of
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
, the language's inability to efficiently return an object of class type from a function was considered a weakness. Around 1991,
Walter Bright Walter G. Bright is an American computer programmer who created the D programming language, the Zortech C++ compiler, and the ''Empire'' computer game. Early life and education Bright is the son of the United States Air Force pilot Charles D. ...
implemented a technique to minimize copying, effectively replacing the hidden object and the named object inside the function with the object used for holding the result: struct Data ; void F(Data* p) int main() Bright implemented this optimization in his Zortech C++ compiler. This particular technique was later coined "Named return value optimization" (NRVO), referring to the fact that the copying of a named object is elided.


Compiler support

Return value optimization is supported on most compilers. There may be, however, circumstances where the compiler is unable to perform the optimization. One common case is when a function may return different named objects depending on the path of execution: #include std::string F(bool cond = false) int main()


External links


Copy elision on cppreference.com


References

{{Compiler optimizations Articles with example C++ code Compiler optimizations C++