How to pass a string to a function correctly?

 

Will the array of characters that make up the string be physically copied when passing it to the function?

That is, will function1() be faster than function2()?

void function1(const string &str)
  {
   // Some action (doesn't matter)
   Print(str);
  }

void function2(string str)
  {
   // Some action (doesn't matter)
   Print(str);
  }

Does it make sense to pass a string by reference if it won't be changed in a function?

 
Vladislav Boyko:

Will the array of characters that make up the string be physically copied when passing it to the function?

Not when it's by reference.

That is, will function1() be faster than function2()?

You should benchmark it. It depends of several factors.

Does it make sense to pass a string by reference if it won't be changed in a function?

Yes possibly.
 
Alain Verleyen #:

You should benchmark it. It depends of several factors.

I think I can't do it because I don't know how compile-time optimization works (and how to disable it). I don't have enough knowledge to do it.


If there is no definite answer, then I think it makes sense to pass strings only by reference (with the const specifier) if they will not change inside the function. I don't think it gets any worse.


An example of a standard function where passing is not by reference:

int  ObjectFind(
   long    chart_id,     // chart identifier
   string  name          // object name
   );

Although it is expected that the name will not be changed. But I think such things in standard functions can be optimized implicitly.

Reason: