0
votes

Here is the quote from standard :

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 to a subobject of which the temporary is bound persists for the lifetime of the reference except as specified below. A temporary bound to a reference member in a constructor’s ctor-initializer (§12.6.2 [class.base.init]) persists until the constructor exits. A temporary bound to a reference parameter in a function call (§5.2.2 [expr.call]) persists until the completion of the full expression containing the call.

Please look at the code :

#include <iostream>
using namespace std;

struct foo{const char* bar ; foo(): bar("This is foo"){} };

foo returnByValue(){ return foo(); }
const foo& returnByConstRef() { return returnByValue();  }

int main() {
std::cout<< returnByConstRef().bar  <<std::endl; // is life of temp is extended in while this expression?
return 0;
}

is the above program valid? or temp object in the following statement dies before return statement leaves the function?

return returnByValue();

if so making the statement

const char*& jinjja = returnByConstRef().bar;

is invalid?

1
How on earth did you manage to quote the first two bullet points and miss the third?T.C.
@T.C. ROFL I feeling dumb now :D . Anyways question originated from this question : stackoverflow.com/questions/2784262/…Angelus Mortis

1 Answers

2
votes

The lifetime of a temporary bound to the returned value in a function return statement (6.6.3) is not extended; the temporary is destroyed at the end of the full-expression in the return statement.

This should answer your question.

It may help to know that when a function returns, the order of events is as follows:

  1. The return value (if any) is initialized by the expression in the return statement (if any). This initialization, which includes the evaluation of the expression, constitutes a full-expression.
  2. Temporaries created in the return statement are destroyed (in reverse order of initialization). (This doesn't include the temporary introduced to hold the return value, in the case that the function's return type is not a reference.)
  3. Automatic local variables are destroyed (in reverse order of initialization).
  4. Control returns to the caller. The full-expression containing the call completes evaluation.
  5. If the function's declared return type is not a reference, the function call expression's value is a temporary. Said temporary, if not bound to a reference, is destroyed along with all the other temporaries created in the full-expression containing the call (in reverse order of initialization).