Suppose I have the following snipplet:
Foo foo;
....
return bar();
Now, does the C++ standard guarantees me that bar() will be called before foo::~Foo() ? Or is this the compiler/implementation's choice?
Thanks!
Suppose I have the following snipplet:
Foo foo;
....
return bar();
Now, does the C++ standard guarantees me that bar() will be called before foo::~Foo() ? Or is this the compiler/implementation's choice?
Thanks!
Just think, what if it was
return bar(foo);
? That just has to work, and it'd be silly if the destruction order was different depending on whether you pass that as an argument or not.Objects destruct when leaving the scope.
return
leaves the scope, but it can't return until it has executedbar()
. Ergo,bar()
is called.The result of calling bar() must be evaluated before the stack frame containing Foo can be cleaned up, so yes, bar() will be called before Foo::~Foo().
It is guaranteed behaviour. The actual execution is unrolled as follows:
Here are some references from the standard:
foo
is of automatic storage duration and:and
and
It is not easy to grasp single idea form details scattered around all the C++ standard. Hopefully, quick overview will help you to make such analysis yourself too.
Yes, bar() will be called before the destructor of foo.
The standard says: 6.6: "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."
The scope isn't left until the return statement is completed.