Why do the const accessors of std::string return a reference?

167 views Asked by At

The std::string accessors (back, front, at, and operator[]) have const and non-const overloads, as below:

char& x();
const char& x() const;

Why does the second version return a const reference, as opposed to simply returning the char by value (as a copy)?

According to the rules of thumb on how to pass objects around, shouldn't small objects be passed by value when there's no need to modify the original?

2

There are 2 answers

9
Benjamin Lindley On BEST ANSWER

Because the caller might want a reference to the char, that reflects any changes made to it through non-const avenues.

std::string str = "hello";
char const& front_ref = static_cast<std::string const&>(str).front();
str[0] = 'x';
std::cout << front_ref; // prints x
0
kfsone On

Because context.

You're dealing with a container and functions with names that imply specific positional data.

std::string s = "hello world?";
const auto& s1 = s.back();
s.back() = '!';

Returning a reference here provides flexibility, it's also consistent with the non-const variants and other stl containers. After all these functions are actually members of std::basic_string<char>.

Remember that "rule of thumb" is a guideline not a rule.