我可以同时为类编写复制和移动赋值运算符吗? [英] Can I write both copy and move assignment operators for a class?
问题描述
这些是我的原型,
MyClass& operator=(MyClass rhs); // copy assignment
MyClass& operator=(MyClass &&rhs); // move assignment
但是当我打电话
MyClass a, b;
a = std::move(b);
,有一个错误.
556 IntelliSense: more than one operator "=" matches these operands:
function "MyClass::operator=(MyClass rhs)"
function "MyClass::operator=(MyClass &&rhs)"
operand types are: MyClass = MyClass
编译器返回:
Error 56 error C2593: 'operator =' is ambiguous
推荐答案
重载解析度不明确,因为当您传递右值时,MyClass
和MyClass &&
都可以由它直接初始化.
Overload resolution is ambiguous because when you pass an rvalue, both MyClass
and MyClass &&
can be directly initialised by it.
如果要提供复制和移动分配的其他实现,则常规方法是通过const引用获取复制分配运算符的参数:
If you want to provide a different implementation of copy and move assignment, the customary way is to take the copy assignment operator's parameter by const reference:
MyClass& operator=(const MyClass &rhs); // copy assignment
MyClass& operator=(MyClass &&rhs); // move assignment
像这样,移动赋值运算符对于(非常量)右值参数严格来说是更好的匹配,因此它是由重载分辨率选择的.
Done like this, the move assignment operator is a strictly better match for a (non-const) rvalue argument and so it's chosen by overload resolution.
另一种称为复制和交换的方法是只提供赋值运算符,按值获取参数,然后使用swap
来实现它:
An alternative approach, called copy-and-swap, is to provide just the assignment operator, take the parameter by value, and use swap
to implement it:
MyClass& operator=(MyClass rhs)
{
swap(*this, rhs);
return *this;
};
这将复制/移动构造函数重新用于分配.它要求您已经实现了一个swap
函数,该函数应该不被抛出.
This reuses the copy/move constructor for the assignment. It requires you to have implemented a swap
function, which should be non-throwing.
这种方法的缺点是,有时手动执行副本分配比执行复制构建并进行移动要便宜.
The downside of this approach is that sometimes, manually implementing copy assignment can be cheaper than performing copy construction followed by a move.
这篇关于我可以同时为类编写复制和移动赋值运算符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!