I came across the following code snippet
std::string&& test()
{
std::string m="Hello";
return (std::move(m));
}
int main()
{
std::string&& m = test();
}
I understand the above code is incorrect and unsafe but I am not sure why.
So far this is my understanding of the code. In the function test
a local
std::string
variable calledm
is created on the stack.This string is then returned however instead of a copy being made its contents are moved to the temporary. At this point the function
test
ends calling the destructor of variablem
(whose contents were moved to the temp)The temporary is now bound to the rvalue reference
m
. And from what I understand is that a temporary will remain alive until its binding object is alive and in scope .
Could someone please tell me where I might be going wrong ? Why is the code above unsafe ?