Search code examples
c++referenceconstantstemporary-objects

What is stack-based reference?


What is stack-based references? How are they different from references that are members of objects? Does the Standard talk about these?

I came across this in an article written by Herb Sutter:

Q1: Is the following code legal C++?

// Example 1

string f() { return "abc"; }

void g() {
const string& s = f();
  cout << s << endl;    // can we still use the "temporary" object?
}

A1: Yes. 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 f() lives until the closing curly brace. (Note this only applies to stack-based references. It doesn’t work for references that are members of objects.)


Solution

  • In the given context, stack-based references means a reference that is an automatic object on the stack.

    That is, in

    // ...
    {
      // ...
      const foo& x = some_foo;
      // ...
    }
    // ...
    

    x is a stack-based object, while the_foo in

    class bar {
      // ...
      foo& the_foo;
      // ...
    };
    

    isn't.