1

In More Effective C++, the following codes are given

const String::CharProxy String::operator[] (int index) const
{
    return CharProxy(const_cast<String&>(*this), index);
}
String::CharProxy::operator char() const
{
    return theString.value->data[charIndex];
}

Why don't we just return a char instead of using const_cast and casting CharProxy to char later?

Bowen Fu
  • 165
  • 8

2 Answers2

0

If I am not wrong in your case there is also the non const version to be able to both read/write the char and also as Real Fresh says to take a pointer/ref of the char.

Then it is natural to offer the same for the const version allowing to read the char (not write of course) and also take a pointer/ref (const) of the char.

You have that behavior with the std::vector std::string etc

bruno
  • 32,421
  • 7
  • 25
  • 37
  • So we will still get the updated char even when someone else modify the String. But actually copy of the String will happen when someone modifies it via non-const CharProxy. Maybe the point is the uniform interface for const and non-const operator []. – Bowen Fu Jan 30 '19 at 02:24
0

You do this so that a String::const_reference (i.e. const String::CharProxy) bound to the return value of [] doesn't suddenly become dangling when somewhere else modifies that particular String.

You could define that mutations invalidated all references, but that would mean your String class would be unusable with a wide range of generic code, and is "Spooky action at a distance". E.g. you have code A first takes a mutable reference from the String, then code B takes a const reference, then A mutates through it's reference. Now code B's reference has become invalidated, and it can't have checked beforehand that this would occur.

Note that the proxy returns the char by value, so no references can escape.

Caleth
  • 52,200
  • 2
  • 44
  • 75
  • This easier solution seems also OK and no dangling reference exists. ```char String::operator[] (int index) const { return value->data[index]; }``` – Bowen Fu Jan 30 '19 at 02:12