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.