Why does this:
#include <string>
#include <iostream>
using namespace std;
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;
}
Give output of:
The answer is:
Instead of:
The answer is: four
Only local
constreferences prolong the lifespan.The standard specifies such behavior in §8.5.3/5, [dcl.init.ref], the section on initializers of reference declarations. The reference in your example is bound to the constructor’s argument
n, and becomes invalid when the objectnis bound to goes out of scope.The lifetime extension is not transitive through a function argument. §12.2/5 [class.temporary]: