string as parameter?

49,396

Solution 1

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.

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.

Share:
49,396
ofey
Author by

ofey

Updated on July 09, 2022

Comments

  • ofey
    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
    ofey about 11 years
    so if i pass by reference and change the string, the original string will be changed? not a copy, unlike java?
  • slugonamission
    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 and String in Java though.
  • ofey
    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
    slugonamission about 11 years
    @ofey yes, since the copied variable is discarded when the function exist.
  • James Kanze
    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
    clockw0rk about 5 years
    this explanation lacks some information without explaining how the stack works