PxxxxR0
Return slot for NRVO

New Proposal,

This version:
http://virjacode.com/papers/returnslot000.htm
Latest version:
http://virjacode.com/papers/returnslot.htm
Author:
TPK Healy <healytpk@vir7ja7code7.com> (Remove all sevens from email address)
Audience:
SG17
Project:
ISO/IEC 14882 Programming Languages — C++, ISO/IEC JTC1/SC22/WG21

Abstract

This proposal introduces a new feature to the C++ programming language for functions that return by value. Programmers gain access to the "return slot" and manually manage the return object. The proposed _Return_slot keyword provides control over the construction and subsequent modification of the return object, enhancing flexibility and efficiency in certain scenarios.

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 _Return_slot 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 Func 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 _Return_slot 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 _Return_slot 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.