【问题标题】:why pass by reference better? [duplicate]为什么通过引用更好? [复制]
【发布时间】:2011-06-20 09:22:57
【问题描述】:

可能重复:
Is it better in C++ to pass by value or pass by constant reference?

查看这两个程序。

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

为什么第二个更好?

【问题讨论】:

    标签: c++


    【解决方案1】:
    【解决方案2】:

    因为它不必复制字符串。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2013-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-27
        • 2014-08-17
        • 1970-01-01
        • 2013-03-24
        相关资源
        最近更新 更多