复制赋值运算符应该按const引用还是按值传递? [英] Should copy assignment operator pass by const reference or by value?

查看:91
本文介绍了复制赋值运算符应该按const引用还是按值传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 11之前,一直都是复制赋值运算符应始终通过const引用传递的情况,如下所示:

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

上面2个运算符的实现如下所示:

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

从C ++ 11开始创建复制赋值运算符时,使用按值传递是个好主意吗?在什么情况下应该这样做?

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?

推荐答案

在C ++ 11之前,总是存在复制赋值运算符应始终通过const引用传递的情况

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).

如果有的话,由于您也具有移动分配运算符,因此在C ++ 11中,此功能.

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

这篇关于复制赋值运算符应该按const引用还是按值传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆