Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When exactly is return value copied

Let's suppose I have following code:

int bar = 0;

struct Foo {
    ~Foo() { bar = 1; }
};

int main(int argc, char ** argv) {
    Foo f;
    return bar;
}

What will be return value of program? 0 or 1?

like image 768
graywolf Avatar asked Feb 04 '26 12:02

graywolf


2 Answers

From [stmt.return]/3:

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.

So the destructor runs after the return value has been initialized, and the return value is thus 0 on the first call of your function.

like image 121
Kerrek SB Avatar answered Feb 07 '26 01:02

Kerrek SB


Automatic variables are removed in the reverse order to their declaration.

So the return value of the function is established before the call to ~Foo().

The return of foobar is therefore a very well-defined 0.

Your question would be more interesting if your function returned int&.

like image 37
Bathsheba Avatar answered Feb 07 '26 01:02

Bathsheba