简体   繁体   中英

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.

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.

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 . 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 . (well, in this case it is probably the same, find is quite simple function).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM