Does a const reference class member 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

6 Answers
6

Leave a Comment