Why return a proxy class even for const member function for "copy on write"?

84 Views Asked by At

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?

2

There are 2 best solutions below

1
bruno On

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

1
Caleth On

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.