Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when are default argument object destroyed?

Tags:

c++

destructor

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 ?

like image 289
GreyGeek Avatar asked Jan 13 '13 23:01

GreyGeek


2 Answers

The default argument will be destroyed at the end of the complete expression that contains the function call.

like image 116
David Rodríguez - dribeas Avatar answered Sep 19 '22 11:09

David Rodríguez - dribeas


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

like image 23
Christian Rau Avatar answered Sep 21 '22 11:09

Christian Rau