Consider the below.
#include <string>
using std::string;
string middle_name () {
return "Jaan";
}
int main ()
{
string&& danger = middle_name(); // ?!
return 0;
}
This doesn’t compute anything, but it compiles without error and demonstrates something that I find confusing: danger is a dangling reference, isn’t it?
If you meant “Is it possible to create dangling rvalue references” then the answer is yes. Your example, however,
is perfectly fine. The same rule applies here that makes this example (article by Herb Sutter) safe as well. If you initialize a reference with a pure rvalue, the life-time of the tempoary object gets extended to the life-time of the reference. You can still produce dangling references, though. For example, this is not safe anymore:
Because
std::movereturns astring&&(which is not a pure rvalue) the rule that extends the temporary’s life-time doesn’t apply. Here,std::movereturns a so-called xvalue. An xvalue is just an unnamed rvalue reference. As such it could refer to anything and it is basically impossible to guess what a returned reference refers to without looking at the function’s implementation.