问题描述
在本文中:
T& T :: operator =(T const& x)// x是对源的引用
{
T tmp(x); // copy construction of tmp does the hard work
swap(* this,tmp); //交易我们的资源tmp的
return * this; //我们的(旧的)资源被销毁与tmp
}
精确,那个配方明显低效!现在显而易见的是,写一个复制和交换任务的正确方法是:
operator =(T x)// x是源的副本;辛苦工作已经做了
{
swap(* this,x); //交易我们的资源for x's
return * this; //我们的(旧的)资源被销毁与x
}
应该通过值而不是通过const引用为值写入赋值运算符。
使用Rvalue引用功能,最好写如下的assignement操作符:
operator =(T&& x)
{
swap(* this,x);
return * this;
}
最后没有区别?
op =
的努力工作。 $ b $
在右值引用上操作可能会
em> be ok,因为如果你调用带有右值表达式作为RHS操作数的 op =
,那么它可能是一个临时对象,调用范围可能不需要/需要使用它了。但是,这不是你的 op =
的工作。 你的中间方法是规范的。 p>
operator =(T x)// x是源的副本;辛苦工作已经做了
{
swap(* this,x); //交易我们的资源for x's
return * this; //我们的(旧的)资源被销毁x
}
In this article http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/comment-page-1/#comment-1877 :
T& T::operator=(T const& x) // x is a reference to the source
{
T tmp(x); // copy construction of tmp does the hard work
swap(*this, tmp); // trade our resources for tmp's
return *this; // our (old) resources get destroyed with tmp
}
but in light of copy elision, that formulation is glaringly inefficient! It’s now "obvious" that the correct way to write a copy-and-swap assignment is:
T& operator=(T x) // x is a copy of the source; hard work already done
{
swap(*this, x); // trade our resources for x's
return *this; // our (old) resources get destroyed with x
}
It is said that we should write assignement operator with argument by value rather than by const reference for copy ellision consideration.
With Rvalue reference feature, is it better to write assignement operator like below ? :
T& operator=(T&& x)
{
swap(*this, x);
return *this;
}
there is finally no difference ?
You want to operate on a copy, otherwise you're removing information from your original object. The idea is to remove information from a temporary copy. It's not highly intuitive but it allows you to use the existing copy constructor and destructor implementations to do the hard work of op=
.
Copy elision is not relevant, because it can't be performed when a copy is semantically required.
Operating on an rvalue reference might be ok, because if you're calling op=
with an rvalue expression as the RHS operand, then it's probably a temporary object and the calling scope probably doesn't want/need to use it any more. However, it's not your op=
's job to assume that.
Your middle approach is canonical.
T& operator=(T x) // x is a copy of the source; hard work already done
{
swap(*this, x); // trade our resources for x's
return *this; // our (old) resources get destroyed with x
}
这篇关于右值引用与赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!