我遇到了https://web.archive.org/web/20120707045924/cpp-next.com/archive/2009/08/want-speed-pass-by-value/ https://web.archive.org/web/20120707045924/cpp-next.com/archive/2009/08/want-speed-pass-by-value/
作者的建议:
不要复制你的函数参数。相反,按值传递它们并
让编译器进行复制。
但是,我不太明白文章中提供的两个示例可以获得什么好处:
// Don't
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
}
vs
// DO
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
}
在这两种情况下都会创建一个额外的变量,那么好处在哪里呢?
我看到的唯一好处是临时对象是否传递到第二个示例中。
要点是,根据操作符的调用方式,副本可能会被省略。假设您像这样使用运算符:
extern T f();
...
T value;
value = f();
如果参数由 by 采取T const&
编译器别无选择,只能保留临时值并将引用传递给赋值运算符。另一方面,当您按值传递参数时,即它使用T
,返回值f()
可以位于该参数所在的位置,从而省略一个副本。当然,如果赋值的参数是某种形式的左值,那么它总是需要复制。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)