1

Consider the code snippets

Foo FuncBar()
{
    return Foo();
}

// some where else
const Foo &myFoo = FuncBar();

Here the life of temporary object Foo() in function FuncBar() is extended by reference to a const myFoo.
Now in the below code snippet

class Sandbox
{
public:
    Sandbox(const string& n) : member(n) {}
    const string& member;
};

int main()
{
    Sandbox sandbox(string("four"));
    cout << "The answer is: " << sandbox.member << endl;
    return 0;
}

Here life of string "four" wasn't prolonged by using reference to const n. Why wasn't it prolonged?
I have checked a few of links like this and this. Still not clear about this.

Community
  • 1
  • 1
user3762146
  • 205
  • 3
  • 13
  • From the accepted answer to the second post you linked to: *Only local const references prolong the lifespan.*. `member` is not a local `const` reference. – R Sahu Mar 14 '17 at 04:25

0 Answers0