1

Am I right, that this (taken from this GotW):

string f() { return "abc"; }

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

is completely fine, while this is not ok at all:

const string& foo() { string x{"abc"}; return x; }
void bar() {
    const string& y = foo();
}

?

Why is it different? Can one say that "the lifetime of a temporay is not extended across a function call (even if bound to a const ref)" ? Or what is an explanation, why the first is ok, but not the second?

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185

1 Answers1

2

The 1st one is pretty fine, because the returned value (which is a temporary) is bound to a reference to const directly, then the lifetime of the temporary is extended to the reference's lifetime.

Note that there's no temporary in the 2nd case, x is a local variable which will be destroyed when get out of the function, then the function will always returns a dangled reference; that reference is used to initialize y but nothing changes, y will be a dangled reference too.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405