为什么编译器试图复制而不是移动 return 值?
Why is the compiler trying to copy instead of moving the return value?
我的代码看起来像
// 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. I understand that the cop constructor is deleted when defining a move constructor (as explained in this post),这似乎不是一个聪明的解决方案)但我不明白如何告诉编译器我想将 'x' 移动到 'result'.
这个:
result = f(); // I am aiming to move 'x' to 'result'
不是尝试移动构造,而是尝试移动分配。而且,正如编译器告诉您的那样:
object of type Foo
cannot be assigned because its copy assignment operator is implicitly deleted
复制赋值运算符被隐式删除(并且移动赋值运算符完全不存在)因为您添加了移动构造函数。据推测,如果您的类型是可移动构造的,那么它也是可移动分配的。所以只需添加:
Foo& operator=(Foo&& ) = default;
我的代码看起来像
// 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. I understand that the cop constructor is deleted when defining a move constructor (as explained in this post),这似乎不是一个聪明的解决方案)但我不明白如何告诉编译器我想将 'x' 移动到 'result'.
这个:
result = f(); // I am aiming to move 'x' to 'result'
不是尝试移动构造,而是尝试移动分配。而且,正如编译器告诉您的那样:
object of type
Foo
cannot be assigned because its copy assignment operator is implicitly deleted
复制赋值运算符被隐式删除(并且移动赋值运算符完全不存在)因为您添加了移动构造函数。据推测,如果您的类型是可移动构造的,那么它也是可移动分配的。所以只需添加:
Foo& operator=(Foo&& ) = default;