c++ - When should I choose copy elision over passing argument by const reference? -


possible duplicate:
is pass-by-value reasonable default in c++11?

i'm reading want speed? pass value. dave abrahams copy elision , rvo. , i'm wondering why need copy elision?

i have been told many times should pass function arguments const reference avoid copying (nearly every c++ book read told me this).

suppose have 2 functions:

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

if actual argument rvalue, copying avoided in both functions. if actual argument lvalue, copying avoided in f1, not in f2. why need feature?

pass value if need copy anyway. whether choose f1's signature or f2's signature depends upon contents of function. example, use const reference in case:

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

but pass value in case:

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

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

Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -