为什么通过参考更好?

时间:2011-02-03 01:27:00

标签: c++

  

可能重复:
  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();
}

为什么第二个更好?

3 个答案:

答案 0 :(得分:0)

因为它不必复制字符串。

答案 1 :(得分:0)

答案 2 :(得分:0)

如果您真的对某些情况感兴趣,那么传递值可能会更好,您可能希望看到this.