我的代码看起来像
// 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'
当我尝试编译时收到
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;
^
我很想试试
return move(x);
但根据 this post 这似乎不是一个聪明的解决方案.我知道在定义 move 构造函数时删除了 cop 构造函数(如 this post 中所述),但我不明白如何告诉编译器我希望将“x” move 到“结果”。
最佳答案
这个:
result = f(); // I am aiming to move 'x' to 'result'
不是尝试 move 构造,而是尝试 move 分配。而且,正如编译器告诉您的那样:
object of type
Foo
cannot be assigned because its copy assignment operator is implicitly deleted
复制赋值运算符被隐式删除(并且 move 赋值运算符完全不存在)因为您添加了 move 构造函数。据推测,如果您的类型是可 move 构造的,那么它也是可 move 分配的。所以只需添加:
Foo& operator=(Foo&& ) = default;
关于c++ - 为什么编译器试图复制而不是 move 返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40388094/