Man*_*ker 8 c++ assignment-operator move-semantics c++11
在C++ 11之前,一直都是复制赋值运算符应该总是通过const引用传递的情况,如下所示:
template <typename T>
ArrayStack<T>& operator= (const ArrayStack& other);
Run Code Online (Sandbox Code Playgroud)
但是,随着移动赋值运算符和构造函数的引入,似乎有些人主张使用pass by value进行复制赋值.还需要添加移动赋值运算符:
template <typename T>
ArrayStack<T>& operator= (ArrayStack other);
ArrayStack<T>& operator= (ArrayStack&& other);
Run Code Online (Sandbox Code Playgroud)
上面的2个运算符实现如下所示:
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;
}
Run Code Online (Sandbox Code Playgroud)
在为C++ 11开始创建复制赋值运算符时,使用pass by值是一个好主意吗?我应该在什么情况下这样做?