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?
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.
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.
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.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With