When is the default argument object destroyed?

void foo(const Object & o = Object()) { return; } 

In the above function, when should ~ Object be called? when does the function exit or when at the end of the block surrounding the call site?

+6
source share
3 answers

The default argument will be destroyed at the end of the full expression containing the function call.

+9
source

To talk a bit about what David said, the standard says in section 12.2 [class.temporary] :

There are two contexts in which the temporary is a different point than the end of the full expression. [...] The second context is when the link is tied to a temporary one. The temporary link to which it is attached, or temporary, which is the full object of the subobject to which the link is attached, is stored for the lifetime of the link, with the exception of:

  • ...
  • The temporary reference to the reference parameter in the function call (5.2.2) is stored until the complete expression containing the call is completed.
  • ...

Thus, they are not destroyed when the function exits, and when the block containing the call ends, but at the end of the complete statement that contains the function call (just said the first semicolon after the function call in the call context).

EDIT: Say we got:

 int foo(const Object & o = Object()); some_stuff(); std::cout << (foo() + 7); other_stuff(); 

This may be roughly equivalent to the following (see concept 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 Michael noted in his comment, this “wording / semicolon” ​​that I gave rather simplifies the term “full expression”, and there are times when this is slightly different, as is its example:

 if(foo()) bar(); 

To destroy a temporary expression before bar is called and therefore different from the expression operator:

 foo() ? bar() : 0; 

But, nevertheless, a semicolon is often good, even if the full expression is not necessarily the same as the operator (which can consist of several full expressions).

+6
source

I do not think this code should compile. You cannot bind a link to a temporary one unless it is const . And if it was const , the temporary should be supported until the end of the function expression. Just like a local variable defined inside it.

0
source

All Articles