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