Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this code legal? (C++0x move semantics)

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;
}
like image 699
Dylan Klomparens Avatar asked Dec 17 '22 11:12

Dylan Klomparens


2 Answers

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.

like image 67
Bo Persson Avatar answered Dec 30 '22 14:12

Bo Persson


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.)

like image 31
fredoverflow Avatar answered Dec 30 '22 14:12

fredoverflow