const string& str

Could someone please explain "const string& str"?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include<string>
using namespace std;

void reverse(const string& str)
{
    size_t numOfChars = str.size();
    if (numOfChars == 1)
        cout << str << endl;
    else
    {
        cout << str[numOfChars - 1];
        reverse(str.substr(0, numOfChars - 1));
    }
}
int main()
{
    string str;
    cout << "\nPlease Enter any string :: ";
    getline(cin, str);
    cout << "\nReverse of String [ " << str << " ] is :: ";
    reverse(str);
    return 0;
}
It passes the string by const reference. This means that the str in your reverse function is a reference to the same object as the one you passed in main. No copy is made. It also means that the reverse function is not allowed to modify the str passed into it.

In other words:
- Passing by reference can void making a copy, which can be expensive for long strings
- Passing with const prevents the function from modifying this reference

A copy would be made if you simply passed by value:
void reverse(const string str)

A better name for your function might be 'print_reversed'.

PS: What happens in your code if str.size() == 0?
Last edited on
Topic archived. No new replies allowed.