I'm curious as to whether this code is legal in C++0x. Specifically, will the object declared in the function move_it()
be properly moved to the object declared in main()
?
#include <iostream>
#include <string>
#include <tr1/memory>
using namespace std;
class x
{
public:
x() { cout << "create " << this << endl; }
~x() { cout << "destroy " << this << endl; }
};
x&& move_it()
{
x r;
return move(r);
}
int main()
{
x n = move_it();
return 0;
}
No, it is returning a reference to a local object, just like with an lvalue reference.
Just return it by value and let x's assumed move constructor pick up the rvalue. When you return by value, the returned object is an rvalue.
If you are lucky, the NRVO optimization will kick in (just like before) and elide the copying anyway.
You are returning a dangling rvalue reference from move_it
, which invokes undefined behavior when you access it in main
.
If you want to move the object, change the return type to x
and get rid of the move:
x move_it()
{
x r;
return r;
}
(Automatic variables are implicitly treated as rvalues when returned from a function.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With