Returning temporary object and binding to const reference

C++ReferenceConstants

C++ Problem Overview


> 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?

C++ Solutions


Solution 1 - C++

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongruszczyView Question on Stackoverflow
Solution 1 - C++Sergey K.View Answer on Stackoverflow