Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why return a const reference for a basic type? (std::string::operator[])

Tags:

c++

oop

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?

like image 337
Paul Avatar asked May 30 '16 21:05

Paul


1 Answers

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.

like image 133
Sam Varshavchik Avatar answered Nov 15 '22 12:11

Sam Varshavchik