我找到了这篇关于C++技术的文章:https://web.archive.org/web/20120707045924/cpp-next.com/archive/2009/08/want-speed-pass-by-value/
作者给出了建议:
不要复制函数参数,相反,通过值传递它们,让编译器完成拷贝。
然而,在文章中提供的两个例子中,我并没有完全理解会有什么好处。
在这两种情况下,都会创建一个额外的变量,那么好处在哪里呢? 我唯一能看到的好处是,在第二个示例中将temp对象传入。
不要复制函数参数,相反,通过值传递它们,让编译器完成拷贝。
然而,在文章中提供的两个例子中,我并没有完全理解会有什么好处。
// 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
}
在这两种情况下,都会创建一个额外的变量,那么好处在哪里呢? 我唯一能看到的好处是,在第二个示例中将temp对象传入。
obj = T();
或obj = foo();
,其中foo()
返回一个T
。 - juanchopanza