简体   繁体   中英

can anyone please explain me the need for & in the first code snippet

In the following snippet of code I have noticed ampersand is used even though we aren't manipulating the string. Can anyone please tell me why it's needed?

bool compare(string &s1,string &s2) 
{ 
    return s1.size() < s2.size(); 
} 

Snippet 2: would this code work?

bool compare(string s1,string s2) 
{ 
    return s1.size() < s2.size(); 
} 

The & sign (reference) is needed, because this way the program will only use a reference to the original string. If you don't use a reference, then the program will copy the string, so the program will be

  • A bit slower
  • Less memory effective

A const reference ( const string& ) is even better, because it will make it read-only, so you can pass string literals. Like compare("abc", "foo bar") .

Yes, your second snippet would work, but it's not recommended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM