2011-02-03 50 views
0

可能重複:
Is it better in C++ to pass by value or pass by constant reference?爲什麼通過引用更好?

看到這些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(); 
} 

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

爲什麼第二個是更好?

回答

0

因爲它不必複製字符串。

相關問題