I am a bit confused about one of the examples in my textbook. When the string is created, it is created as type string
. However, when the same string is passed into a function, the function parameters are of const string
and not string
.
Here's the part of the code:
int main()
{
string str;
cout << "blah blah..";
getline(cin, str);
if (is_pal(str))
//...
}
bool is_pal(const string& s)
{
//...
}
Why is the function parameter const string& s
instead of just string& s
? I've read through my textbook but can't seem to find any explanation for this.
Objects that may be expensive to copy, such as std::string
, are very often passed by const lvalue reference in C++. This is a very common idiom; you will see it everywhere. A const lvalue reference can bind to both lvalues and rvalues without making any copies, so this is an efficient way to pass strings to functions that will not modify them.
When a function uses const
on its argument, it typically means the function will not alter the argument.
When you are writing your own functions, you should determine if the function intends to modify the argument or not, and use or not use const
accordingly.
Likewise, when you are using functions that someone else has written, pay attention to whether or not the function intends to modify your object or not. This is made known to you if the function accepts a non-const
reference.
void foo_will_not_modify (const std::string &x); // const ref - won't modify
void bar_will_not_modify (std::string x); // copy - won't modify
void baz_will_modify (std::string &x); // reference - can modify
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With