void foo(const Object & o = Object()) {
return;
}
In the function above, when is ~Object supposed to be called ? when the function exit or when at the end of the block surrounding the call site ?
The default argument will be destroyed at the end of the complete expression that contains the function call.
To elaborate a bit on what David said, the standard says in section 12.2 [class.temporary]:
There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression. [...] The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except:
- ...
- A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full-expression containing the call.
- ...
So they are neither destroyed when the function exits nor when the block containing the call ends, but at the end of the complete statement that contains the function call (simply said, at the first semicolon after the function call, in the calling context).
EDIT: So say we got:
int foo(const Object & o = Object());
some_stuff();
std::cout << (foo() + 7);
other_stuff();
This sould be roughly equivalent to the following (mind the conceptual scope block):
some_stuff();
{
Object o; // create temprorary
int i = foo(o); // and use it
int j = i + 7; // do other things
std::cout << j; // while o still alive
} // finally destroy o
other_stuff();
EDIT: As pointed out by Michael in his comment, this "statement/semicolon"-analogy I gave is rather a simplification of the term "full-expression" and there are cases where it is a bit different, like his example:
if(foo()) bar();
Which would destroy the temporary before bar
is called and thus be different from the expression statement:
foo() ? bar() : 0;
But nevertheless, the "semicolon"-analogy is often a good fit, even if a full-expression is not neccessarily the same as a statement (which can consist of multiple full-expressions).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With