cpp/language/copy elision

Omits copy constructors, resulting in zero-copy pass-by-value semantics.

Explanation
{{rrev|since=c++17|

Mandatory elision of copy/move operations
Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. The copy/move constructors need not be present or accessible:
 * In a, when the operand is a of the same class type (ignoring ) as the function return type:


 * The destructor of the type returned must be accessible at the point of the return statement and non-deleted, even though no T object is destroyed.


 * In the initialization of an object, when the initializer expression is a of the same class type (ignoring ) as the variable type:


 * This can only apply when the object being initialized is known not to be a potentially-overlapping subobject:

Note: the rule above does not specify an optimization: C++17 core language specification of and  is fundamentally different from that of the earlier C++ revisions: there is no longer a temporary to copy/move from. Another way to describe C++17 mechanics is "unmaterialized value passing": prvalues are returned and used without ever materializing a temporary. }}

Non-mandatory elision of copy operations
Under the following circumstances, the compilers are permitted, but not required to omit the copy construction of class objects even if the copy constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. This is an optimization: even when it takes place and the copy constructor is not called, it still must be present and accessible (as if no optimization happened at all), otherwise the program is ill-formed:
 * In a, when the operand is the name of a non-volatile object with automatic storage duration, which isn't a function parameter or a catch clause parameter, and which is of the same class type (ignoring ) as the function return type. This variant of copy elision is known as NRVO, "named return value optimization".

When copy elision occurs, the implementation treats the source and target of the omitted copy operation as simply two different ways of referring to the same object, and the destruction of that object occurs at the later of the times when the two objects would have been destroyed without the optimization.

Multiple copy elisions may be chained to eliminate multiple copies.