Search code examples
c++functionconstructormovervalue-reference

Why is the compiler trying to copy instead of moving the return value?


My code looks like

// definition of class 'Foo'
class Foo
{
  private:
    vector<Bar> v;
  public:
    ...
    Foo(Foo&&) = default; // move constructor
};

// definition of function 'f'
Foo f()
{
  Foo x;
  DoStuff(x);
  return x;
}

// Somewhere in main
result = f(); // I am aiming to move 'x' to 'result'

When I try to compile I receive

EAL_1.6.cpp:314:13: error: object of type 'Foo' cannot be assigned because its copy assignment operator is implicitly deleted
        x = f(x);
            ^
EAL_1.6.cpp:232:5: note: copy assignment operator is implicitly deleted because 'Foo' has a user-declared move constructor
    Foo(Foo&&) = default;
    ^

I was tempted to try

return move(x);

but it does not appear to be a clever solution according to this post. I understand that the cop constructor is deleted when defining a move constructor (as explained in this post) but I don't understand how to tell the compiler that I would like 'x' to be moved to 'result'.


Solution

  • This:

    result = f(); // I am aiming to move 'x' to 'result'
    

    isn't an attempt at move construction, it's an attempt at move assignment. And, as the compiler is telling you:

    object of type Foo cannot be assigned because its copy assignment operator is implicitly deleted

    The copy assignment operator is implicitly deleted (and the move assignment operator is simply absent entirely) because you added the move constructor. Presumably, if your type is move constructible, it's also move assignable. So just add:

    Foo& operator=(Foo&& ) = default;