The signatures of the operator std::string::operator[]
are:
char& operator[] (size_t pos);
const char& operator[] (size_t pos) const;
Why does the const version return const char&
, and not just char
?
Because the whole purpose of a const
object is that it cannot be modified. If a const
class member, in this case, returns a mutable reference to a character in the string, you could modify it.
Now, as far as operator[]
goes, it's because you can use the &
operator to obtain a pointer to it. After all, something like this is fairly common:
auto *foo=&bar[baz];
You wouldn't be able to do it with a plain rvalue return type. At least you can get a const
pointer, in this case.
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