0

Possible Duplicate:
Is it better in C++ to pass by value or pass by constant reference?

see these 2 program.

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

and

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

Why second one is better?

Community
  • 1
  • 1
Josh Morrison
  • 7,288
  • 24
  • 65
  • 85

3 Answers3

0

Because it doesn't have to copy the strings.

Daniel A. White
  • 181,601
  • 45
  • 354
  • 430
0

I suggest you read this SO Question - Is it better in C++ to pass by value or pass by constant reference?

Community
  • 1
  • 1
Andrew White
  • 51,542
  • 18
  • 111
  • 135
0

If you're really interested in some cases when passing by value may be better, you might want to see this.

Yippie-Ki-Yay
  • 21,160
  • 25
  • 87
  • 145