Yves
Yves

Reputation: 12371

An rvalue reference in C++ prolongs the life of a temporary object

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?

Upvotes: 2

Views: 562

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118300

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.

Upvotes: 1

Related Questions