为什么编译器试图复制而不是移动返回值?

Rem*_*i.b 1 c++ constructor function move rvalue-reference

我的代码看起来像

// 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'
Run Code Online (Sandbox Code Playgroud)

当我尝试编译时,我收到了

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;
    ^
Run Code Online (Sandbox Code Playgroud)

我很想尝试

return move(x);
Run Code Online (Sandbox Code Playgroud)

但根据这篇文章,它似乎并不是一个聪明的解决方案.据我所知,警察构造函数定义移动构造函数时删除(说明这篇文章),但我不知道如何告诉,我想"X"被移动到"结果"的编译器.

Bar*_*rry 7

这个:

result = f(); // I am aiming to move 'x' to 'result'
Run Code Online (Sandbox Code Playgroud)

这不是移动建设的尝试,而是移动任务的尝试.而且,正如编译器告诉你的那样:

Foo无法分配类型的对象,因为隐式删除了其复制赋值运算符

隐式删除了复制赋值运算符(并且完全没有移动赋值运算符),因为您添加了移动构造函数.据推测,如果你的类型是可移动的,那么它也是可移动的.所以只需添加:

Foo& operator=(Foo&& ) = default;
Run Code Online (Sandbox Code Playgroud)