2023-06-06

What's the order of destruction of function parameters and return values?

In the following code:

struct Foo {
    void Func();
    ~Foo();
};

Foo GetFoo(Foo foo);

The function GetFoo accepts a parameter foo by value and returns a Foo object. If we call GetFoo by this way:

Foo f;
GetFoo(f).Func();

Will the parameter foo or the return value object destruct first according to the C++ standard?


C++17 says in expr.call#4 that the implementation can choose whether to destruct the parameter object when the function returns or at the end of the enclosing full-expression:

It is implementation-defined whether the lifetime of a parameter ends when the function in which it is defined returns or at the end of the enclosing full-expression.

And in class.temporary#4 it also says a temporary object (the return value object) is destroyed as the last step in evaluating the full-expression:

Temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created.

Then if the implementation chooses to destruct parameter objects at the end of the enclosing full-expresion, which will destruct first, according to C++ standard?



No comments:

Post a Comment