2

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Yves
  • 11,597
  • 17
  • 83
  • 180
  • 2
    the lifetime of temporary matches the lifetime of the reference that binds directly to it, which is `n` (not `member`) – M.M May 18 '16 at 02:50
  • @M.M Will `string&& member` make sense? – songyuanyao May 18 '16 at 02:53
  • @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 May 18 '16 at 02:58
  • @songyuanyao no, the lifetime of temporary matches the lifetime of `n`, not `member` – M.M May 18 '16 at 03:00
  • @M.M So OP's code is still ill-formed? – songyuanyao May 18 '16 at 03:02
  • @songyuanyao well, I dont think you can change `member` into rvalue ref. Because `n` is a left reference. `int &&rr1 = 42; int &&rr2 = rr1; // error, rr1 is a left value`. – Yves May 18 '16 at 03:02
  • It's well-formed but causes undefined behaviour – M.M May 18 '16 at 03:03
  • @M.M I don't quite understand "binds directly to it". What if I code this:`const int & r = 6; func(r);` And here is the func: `void func(const int &n){}`. does "binds directly to it" mean that `n` in the func is undefined behaviour? – Yves May 18 '16 at 03:07
  • @Thomas no, because the temporary's lifetime matches `r`, and `n`'s lifetime is a subset of `r` – M.M May 18 '16 at 03:20
  • Is it because `6` is always there so `func` can work whereas `string("four")` will be free after the ctor? – Yves May 18 '16 at 03:24
  • no, nothing like that – M.M May 18 '16 at 03:34

1 Answers1

1

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.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148