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?
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();
}