string as parameter?
Solution 1
String literals are immutable, std::string
s 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.
Solution 2
Yes, there will be a difference.
The second variant (without the &
) will copy the string by value into the scope of the getString
function. This means that any updates you make will affect the local copy, not the caller's copy. This is done by calling the class's copy constructor with the old value (std::string(std::string& val)
).
On the other hand, the first variant (with the &
) passes by reference, so changing the local variable will change the caller's variable, unless the reference is marked as const (in which case, you cannot change the value). This should be faster since no copy operation needs to happen if you are not changing the string.
ofey
Updated on July 09, 2022Comments
-
ofey almost 2 years
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++?
-
ofey about 11 yearsso if i pass by reference and change the string, the original string will be changed? not a copy, unlike java?
-
slugonamission about 11 years@ofey - yes, but last time I used Java I'm pretty sure that class types (i.e. non-fundamental) types are also passed by reference, not value. It may be a difference between
string
andString
in Java though. -
ofey about 11 years@slugonamission so if i want to change a huge string and i don't care about saving its original value, i should pass it by reference and no local copy shall be made?
-
slugonamission about 11 years@ofey yes, since the copied variable is discarded when the function exist.
-
James Kanze about 11 years@ofey Not at all like Java. In C++, strings have value semantics, and are mutable. In Java, they have reference semantics, and are immutable.
-
clockw0rk about 5 yearsthis explanation lacks some information without explaining how the stack works