Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why pass a string by reference and make it a constant?

Tags:

c++

Just a general question say the signature of a function is:

void f( const string & s )...

Why is it necessary to pass this by reference if you are not actually changing the string (since it is constant)?

like image 755
user2809437 Avatar asked Feb 01 '26 10:02

user2809437


1 Answers

There are two alternatives to passing by reference - passing by pointer, and passing by value.

Passing by pointer is similar to passing by reference: the same argument of "why pass a pointer if you do not want to modify it" could be made for it.

Passing by value requires making a copy. Copying a string is usually more expensive, because dynamic memory needs to be allocated and de-allocated under the cover. That is why it is often a better idea to pass a const reference / pointer than passing a copy that you are not planning to change.

like image 57
Sergey Kalinichenko Avatar answered Feb 03 '26 04:02

Sergey Kalinichenko