string and string&

Dec 2, 2010 at 5:30pm
as for function with string type parameters
void func(string s)

for efficiency purpose, should it be always like
void func(string& s) instead of func(string s)?

Is there any case a string instead of string& should be used as a function parameter?

Thanks

Chris
Dec 2, 2010 at 5:42pm
Well that depends... do you really always want to modify the string argument?
Dec 2, 2010 at 5:43pm
No, not for strings, but for built-in types there is no difference. Finally, there is still an alternative to a normal reference (or pointer), a constant reference (or pointer), this way, you have advantage of both ways: No direct access to the actual value, but faster to pass it then by value.
To pass by constant reference, prefix the type name with const:
void foo(const string& s) // Faster passing, but the function cannot edit s directly
Dec 2, 2010 at 6:05pm
No direct access to the actual value, but faster to pass it then by value.

Well, technically, you are accessing the actual object directly, but you can only read it, not write to it. Even that can be bypassed with a cast, though.
Topic archived. No new replies allowed.