Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a string passed as const string in a function parameter

Tags:

c++

string

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.

like image 665
ruisen Avatar asked Apr 27 '15 22:04

ruisen


2 Answers

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.

like image 174
Brian Bi Avatar answered Sep 17 '22 07:09

Brian Bi


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
like image 44
jxh Avatar answered Sep 17 '22 07:09

jxh