2011-02-03 2 views
0

Possible en double:
Is it better in C++ to pass by value or pass by constant reference?pourquoi passer par référence mieux?

voir ces programmes 2.

bool isShorter(const string s1, const string s2); 

int main() 
{ 
    string s1 = "abc"; 
    string s2 = "abcd"; 
    cout << isShorter(s1,s2); 
} 

bool isShorter(const string s1, const string s2) 
{ 
    return s1.size() < s2.size(); 
} 

et

bool isShorter(const string &s1, const string &s2); 

int main() 
{ 
    string s1 = "abc"; 
    string s2 = "abcd"; 
    cout << isShorter(s1,s2); 
} 

bool isShorter(const string &s1, const string &s2) 
{ 
    return s1.size() < s2.size(); 
} 

Pourquoi second est le meilleur?

Répondre

0

Parce qu'il ne doit pas copier les chaînes.

0

Si vous êtes vraiment intéressé dans certains cas, en passant par la valeur peut être mieux, vous pouvez voir this.