I need a few clarification regarding const reference.
From this link:
const Foo &myFoo = FuncBar();
const reference extended the life of the local object. But when I checked this link although they used a const reference
Sandbox(const string& n) : member(n) {}
the lifetime of string "four" did not increase.
Sandbox sandbox(string("four"));
They used the sentence
Only local const references prolong the lifespan.
Then in the second link isn't the string "four" local to the main function and shouldn't the const reference n prolong its life?
So why isn't the lifetime getting prolonged in the second link?
The two links which you have referred are different in the sense that one shows the use of a local const reference and other shows the use of a class member const reference.
When we create local const references and refer to a temporary object then in this compiler extends the life of the temporary till the scope of local const reference.
Class member const reference pointing to temporary will lead to unexpected results as the life of the temporary object will not be extended beyond the constructor invoked to initialize class member reference. As explained in one of the answers the temporary will only survive till completion of the constructor.
Quoting the answer from: Does a const reference prolong the life of a temporary?
If you analyze it correctly you will realize that in both cases the life of temporary is extended till the scope from where the references are initialized is valid. As soon as the scope from where reference goes out of scope the temporary becomes invalid.
For local const reference, scope is inside a function from where it is being initialized to a temp. For class member const reference, scope is constructor where it is being initialized to a temp.
You should also read this GOTW article: https://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/