简体   繁体   English

复制赋值运算符应该通过const引用还是按值传递?

[英]Should copy assignment operator pass by const reference or by value?

Prior to C++11, it has always been the case that copy assignment operator should always pass by const reference, like so: 在C ++ 11之前,一直都是复制赋值运算符应该总是通过const引用传递的情况,如下所示:

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. 但是,随着移动赋值运算符和构造函数的引入,似乎有些人主张使用pass by value进行复制赋值。 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: 上面的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;
}

Is it a good idea to use pass by value when creating copy assignment operator for C++11 onwards? 在为C ++ 11开始创建复制赋值运算符时,使用pass by值是一个好主意吗? Under what circumstances should I do so? 我应该在什么情况下这样做?

Prior to C++11, it has always been the case that copy assignment operator should always pass by const reference 在C ++ 11之前,一直都是复制赋值运算符应始终通过const引用的情况

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. 如果有的话,这个现在你有一个移动赋值操作符太是C ++ 11 的那么有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 复制赋值运算符中的值传递与引用传递 - Pass by value vs. pass by reference in copy assignment operator 为什么复制赋值运算符必须返回引用/ const引用? - Why must the copy assignment operator return a reference/const reference? C++:赋值运算符:按值传递(复制和交换)与按引用传递 - C++: assignment operator: pass-by-value (copy-and-swap) vs pass-by-reference 为什么复制赋值运算符的参数应该是引用? - Why should the parameter to a copy assignment operator should be a reference? 我应该在operator =中使用pass-by-const-reference吗? - Should I use pass-by-const-reference in operator=? 我应该在模板函数中按const引用还是按值传递? - Should I pass by const reference or by value in a template function? 为什么`std::string` 的赋值运算符按值获取`char` 而不是`const` 引用? - Why `std::string`'s assignment operator take `char` by value and not `const` reference? 复制ctor和复制分配运算符const关键字位置 - Copy ctor and copy assignment operator const keyword position 当复制构造函数和赋值运算符被禁用时,将引用实例传递给 static 方法 - Pass reference instance to static method when copy-constructor and assignment-operator is disabled 为什么赋值运算符应该返回对对象的引用? - Why should the assignment operator return a reference to the object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM