【发布时间】:2013-09-20 10:15:12
【问题描述】:
我遇到了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
}
对
// 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
}
在这两种情况下都会创建一个额外的变量,那么好处在哪里? 我看到的唯一好处是,如果将临时对象传递到第二个示例中。
【问题讨论】:
-
如果源是临时的:
obj = T();或obj = foo();其中foo()返回T。 -
这实际上不是很好的建议。它在接口中暴露了应该是实现细节(无论是否复制参数),这是非常糟糕的软件工程。有时分析器会说您必须这样做,但除此之外,您必须遵守编码指南。 (普遍的指导方针似乎是通过引用传递类类型,其他一切都通过值,尽管这也可能被视为过早的优化。)
-
@jameskanze “这个函数复制参数的状态”是一个合理的接口特性。除其他外,它会影响成本,它会告诉您必须实现参数类型的哪些功能,甚至会告知用户有关功能的信息。 C++11 的部分天才之处在于复制和移动很重要,并且对数据进行分区操作,并且将其暴露出来很重要。
标签: c++ compiler-optimization copy-elision