Can I write both copy and move assignment operators for a class?

左心房为你撑大大i 提交于 2019-12-04 17:06:45

Overload resolution is ambiguous because when you pass an rvalue, both MyClass and MyClass && can be directly initialised by it.

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.

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;
};

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!