[英]Differences between pass-by-value and pass-by-reference in c++
I'm wondering which of the following two functions is the most efficient in terms of time and space. 我想知道以下两个函数中哪个在时间和空间上最有效。 They both check for the existence of a certain element in the stack. 它们都检查堆栈中是否存在某个元素。 The first one uses pass-by-value mechanism, while the second one uses pass-by-reference. 第一个使用值传递机制,第二个使用引用传递。 I may be wrong but I think that the pass-by-value mechanism copies the parameters implicitly, while in the pass-by-ref we do it explicitly. 我可能是错的,但我认为传递值机制会隐式复制参数,而在传递引用中我们会显式地进行复制。
First Version passed-by-value: 第一版按值传递:
template<class T>
bool find (stack<T> source, T value)
{
while (!source.isEmpty() && source.top() != value)
source.pop();
if (!source.isEmpty())
return true;
return false;
}
Second Version passed-by-reference : 通过引用传递的第二版:
template<class T>
bool find (const stack<T> &source, T value)
{
stack<T> temp = source;
while (!temp.isEmpty() && temp.top() != value)
temp.pop();
if (!temp.isEmpty())
return true;
return false;
} }
If you're going to be making a local copy inside the function anyway, use pass by value. 如果仍然要在函数内部进行本地复制,请使用按值传递。 It's simpler, and simpler is usually good. 它更简单,通常更简单。
PS when you're returning a bool
result you don't usually need an if
statement for it. PS,当您返回bool
结果时,通常不需要if
语句。
return !source.isEmpty();
It is definitely better to pass it by value in this case. 在这种情况下,最好通过值传递它。 As Mark said, your pass-by-reference version makes a copy anyway. 就像Mark所说的那样,您的按引用传递版本仍会进行复制。
In this case, pass-by-value is better, because you give more information to compiler and therefore it may be able to do better optimizations. 在这种情况下,按值传递会更好,因为您可以向编译器提供更多信息,因此它可以进行更好的优化。 You guarantee that inside your find
function source
is really a value belonging only to find
. 您保证在find
函数source
中实际上是一个仅属于find
的值。 When you pass-by-reference some value, compiler can't tell, whether there is some other (non-const) reference to same instance, which can modify source
while executing find
. 当您按引用传递某个值时,编译器无法分辨是否存在对同一实例的其他(非const)引用,这些引用可以在执行find
修改source
。 (well, in this case it is probably the same, find
is quite simple function). (好吧,在这种情况下可能是相同的, find
是相当简单的功能)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.