1. Introduction
C++ is a powerful programming language known for its efficiency and
flexibility. However, certain scenarios require finer control over the
creation of return objects from functions, in particular where a local
variable is modified after its construction and then returned by value.
This proposal introduces a new feature, the
keyword, which
enables programmers to directly manipulate the return object’s memory
location.
2. Motivation
The current mechanism for returning objects from functions in C++ relies on implicit construction and return-by-value semantics. While this approach is suitable for most cases, it lacks flexibility in situations where manual control over the return object is desired, in particular where the return type is both unmovable and uncopyable. Consider the following function:
mutex Func ( void ) { mutex m ; m . lock (); return m ; // compiler error }
In the above example, the function
creates a mutex object, locks
it, and then tries to return it by value. This code fails to compile with
a C++23 compiler though, because the return type is both unmovable and
uncopyable.
By introducing the
keyword, programmers gain direct access
to the memory location where the return object will be stored. This
achieves Named Return Value Optimisation (NRVO), as demonstrated in
the following modified version of Func:
mutex Func ( void ) _Return_slot { auto & m = *:: new ( _Return_slot ) mutex ; try { m . lock (); } catch (...) { m . ~ mutex (); throw ; } }
With the
keyword, the programmer can manually construct
the return object in the designated memory location. Additionally,
exception safety is preserved through manual invocation of the destructor
in case of exceptions thrown after the object is constructed.