C++ 为什么通过参考传递更好?

C++ 为什么通过参考传递更好?,c++,C++,可能重复: 看这两个节目 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();
}


为什么第二个更好?

因为它不必复制字符串。

我建议您阅读此

如果您真的对某些情况感兴趣,那么按值传递可能更好,您可能想看看

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