Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string as parameter?

Tags:

If i am not going to modify a string then is the first option better or are both same- (I just want to iterate through the string, but since string size is big I don't want local copy to be made.)

int getString(string& str1) {
    //code
}


int getString (string str1) {
    //code
}

And if I do plan on changing the string, then is there any difference between the two? Is it because strings are immutable in C++?

like image 690
ofey Avatar asked Feb 04 '13 19:02

ofey


1 Answers

String literals are immutable, std::strings are not.

The first one is pass-by-reference. If you don't plan on modifying the string, pass it by const reference.

The second is pass-by-value - if you do modify the string inside the function, you'd only be modifying a copy, so it's moot.

like image 92
Luchian Grigore Avatar answered Oct 11 '22 05:10

Luchian Grigore