Returning temporary object and binding to const reference [duplicate]

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.

Leave a Comment