Exact moment of “return” in a C++-function

Due to Return Value Optimization (RVO), a destructor for std::string res in make_string_ok may not be called. The string object can be constructed on the caller’s side and the function may only initialize the value.

The code will be equivalent to:

void make_string_ok(std::string& res){
    Writer w(res);
}

int main() {
    std::string res("A");
    make_string_ok(res);
}

That is why the value return shall be “AB”.

In the second example, RVO does not apply, and the value will be copied to the returned value exactly upon the call to return, and Writer‘s destructor will run on res.first after the copy occurred.

6.6 Jump statements

On exit from a scope (however accomplished), destructors (12.4) are
called for all constructed objects with automatic storage duration
(3.7.2) (named objects or temporaries) that are declared in that
scope, in the reverse order of their declaration. Transfer out of a
loop, out of a block, or back past an initialized variable with
automatic storage duration involves the destruction of variables with
automatic storage duration that are in scope at the point transferred
from…

6.6.3 The Return Statement

The copy-initialization of the returned entity is sequenced before the
destruction of temporaries at the end of the full-expression
established by the operand of the return statement, which, in turn, is
sequenced before the destruction of local variables (6.6) of the block
enclosing the return statement.

12.8 Copying and moving class objects

31 When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the
copy/move constructor and/or destructor for the object have side
effects. In such cases, the implementation treats the source and
target of the omitted copy/move 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.(123) This elision of copy/move
operations, called copy elision, is permitted in the following
circumstances (which may be combined to eliminate multiple copies):

— in a return statement in a function with a class return type, when
the expression is the name of a non-volatile automatic object (other
than a function or catch-clause parameter) with the same cvunqualified
type as the function return type, the copy/move operation can be
omitted by constructing the automatic object directly into the
function’s return value

123) Because only one object is destroyed instead of two, and one
copy/move constructor is not executed, there is still one object
destroyed for each one constructed.

Leave a Comment