Should copy assignment operator pass by const reference or by value?

南笙酒味 提交于 2021-02-06 11:15:55

问题


Prior to C++11, it has always been the case that copy assignment operator should always pass by const reference, like so:

template <typename T>
ArrayStack<T>& operator= (const ArrayStack& other);

However, with the introduction of move assignment operators and constructors, it seems that some people are advocating using pass by value for copy assignment instead. A move assignment operator also needs to be added:

template <typename T>
ArrayStack<T>& operator= (ArrayStack other);
ArrayStack<T>& operator= (ArrayStack&& other);

The above 2 operator implementation looks like this:

template <typename T>
ArrayStack<T>& ArrayStack<T>::operator =(ArrayStack other)
{
    ArrayStack tmp(other);
    swap(*this, tmp);
    return *this;
}

template <typename T>
ArrayStack<T>& ArrayStack<T>::operator =(ArrayStack&& other)
{
    swap(*this, other);
    return *this;
}

Is it a good idea to use pass by value when creating copy assignment operator for C++11 onwards? Under what circumstances should I do so?


回答1:


Prior to C++11, it has always been the case that copy assignment operator should always pass by const reference

That is not true. The best approach has always been to use the copy-and-swap idiom, and that's what you're seeing here (although the implementation in the body is sub-optimal).

If anything, this is less useful in C++11 now that you have a move assignment operator too.



来源:https://stackoverflow.com/questions/38808504/should-copy-assignment-operator-pass-by-const-reference-or-by-value

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