2
votes

With the Stack Overflow question Does a const reference prolong the life of a temporary?, I understand how a const reference prolongs the life of a temporary object.

I know an rvalue reference can prolong the life of a temporary object too, but I don't know if there is some difference.

So if I code like this:

#include <string>
#include <iostream>
using namespace std;

class Sandbox
{
public:
    Sandbox(string&& n) : member(n) {}
    const string& member;
};

int main()
{
    Sandbox sandbox(string("four"));
    cout << "The answer is: " << sandbox.member << endl;
    return 0;
}

Will it work or will it have the same error like the link above?

What if I code like the following?

class Sandbox
{
public:
    Sandbox(string&& n) : member(move(n)) {}
    const string&& member;
};

Will it work?

1
the lifetime of temporary matches the lifetime of the reference that binds directly to it, which is n (not member)M.M
@M.M Will string&& member make sense?songyuanyao
@M.M I meant does changing member rvalue reference make OP's code valid? Does the temporary string("four") 's life prolonged until the cout statement?songyuanyao
@songyuanyao no, the lifetime of temporary matches the lifetime of n, not memberM.M
@M.M So OP's code is still ill-formed?songyuanyao

1 Answers

1
votes

The string("four") temporary exists for the duration of the constructor call (this is explained in the answer to the linked question). Once the object is constructed, this temporary gets destroyed. The reference in the class is now a reference to a destroyed object. Using the reference results in undefined behavior.

The use of the rvalue reference, here, makes no difference.