Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I choose copy elision over passing argument by const reference? [duplicate]

Possible Duplicate:
Is pass-by-value a reasonable default in C++11?

I'm reading Want Speed? Pass by Value. by Dave Abrahams about copy elision and RVO. And I'm wondering why do we need the copy elision?

I have been told too many times that you should pass function arguments by const reference to avoid copying (nearly every c++ book I read told me about this).

Suppose we have two functions:

int f1(const string &s);
int f2(string s);

If the actual argument is an rvalue, copying will be avoided in both functions. But if the actual argument is an lvalue, copying will only be avoided in f1, not in f2. So why do we need this feature?

like image 1000
amazingjxq Avatar asked Jul 07 '12 09:07

amazingjxq


People also ask

What is the difference between pass by reference and pass by const reference?

From what I understand: when you pass by value, the function makes a local copy of the passed argument and uses that; when the function ends, it goes out of scope. When you pass by const reference, the function uses a reference to the passed argument that can't be modified.

Why is it usually better to pass objects by reference than by value?

The reason is simple: if you passed by value, a copy of the object had to be made and, except for very small objects, this is always more expensive than passing a reference.

When should you pass by reference?

If an argument is significant in size (like a string that's a list), it makes more sense to use pass by reference to avoid having to move the entire string. Effectively, pass by reference will pass just the address of the argument and not the argument itself.

Is it better to pass by reference?

2) For passing large sized arguments: If an argument is large, passing by reference (or pointer) is more efficient because only an address is really passed, not the entire object.


1 Answers

Pass by value if you need a copy anyway. Whether you choose f1's signature or f2's signature depends upon the contents of the function. For example, you would use a const reference in this case:

int f1(const string& s) {
    return s.size();
}

But you would pass by value in this case:

int f2(string s) {
    sort(s.begin(), s.end());
    s.erase(unique(s.begin(), s.end()), s.end());
    return s.size();
}

because the alternative would be this:

int f2(const string& s) {
    string temp(s);
    sort(temp.begin(), temp.end());
    temp.erase(unique(temp.begin(), temp.end()), temp.end());
    return temp.size();
}
like image 97
Benjamin Lindley Avatar answered Sep 26 '22 01:09

Benjamin Lindley