Kyle Kyle - 2 months ago 20
C++ Question

Does a const reference prolong the life of a temporary?

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

Answer

Only local const references 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 object n is bound to goes out of scope.

The lifetime extension is not transitive through a function argument. §12.2/5 [class.temporary]:

The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object to a subobject of which the temporary is bound persists for the lifetime of the reference except as specified below. A temporary bound to a reference member in a constructor’s ctor-initializer (§12.6.2 [class.base.init]) persists until the constructor exits. A temporary bound to a reference parameter in a function call (§5.2.2 [expr.call]) persists until the completion of the full expression containing the call.