Returning temporary object and binding to const reference [duplicate]

Possible Duplicate:
Does a const reference prolong the life of a temporary?

My compiler doesn't complain about assigning temporary to const reference:

string foo() {
  return string("123");
};

int main() {
  const string& val = foo();
  printf("%s\n", val.c_str());
  return 0;
}

Why? I thought that string returned from foo is temporary and val can point to object which lifetime has finished. Does C++ standard allow this and prolongs the lifetime of returned object?


This is a C++ feature. The code is valid and does exactly what it appears to do.

Normally, a temporary object lasts only until the end of the full expression in which it appears. However, C++ deliberately specifies that binding a temporary object to a reference to const on the stack lengthens the lifetime of the temporary to the lifetime of the reference itself, and thus avoids what would otherwise be a common dangling-reference error. In the example above, the temporary returned by foo() lives until the closing curly brace.

P.S: This only applies to stack-based references. It doesn’t work for references that are members of objects.

Full text: GotW #88: A Candidate For the “Most Important const” by Herb Sutter.