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?
n
(notmember
) – M.Mstring&& member
make sense? – songyuanyaomember
rvalue reference make OP's code valid? Does the temporarystring("four")
's life prolonged until the cout statement? – songyuanyaon
, notmember
– M.M