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,488
  • 25
  • 67
  • 86

3 Answers3

0

Because it doesn't have to copy the strings.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
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
  • 52,720
  • 19
  • 113
  • 137
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
  • 22,026
  • 26
  • 90
  • 148