Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 367
emlai Avatar asked Apr 27 '26 07:04

emlai


1 Answers

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
like image 199
Benjamin Lindley Avatar answered Apr 28 '26 19:04

Benjamin Lindley