graywolf
graywolf

Reputation: 7470

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?

Upvotes: 2

Views: 198

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 476940

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.

Upvotes: 12

Bathsheba
Bathsheba

Reputation: 234635

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&.

Upvotes: 2

Related Questions