On Mon, 18 Oct 2010 15:43:29 -0400, Rainer Deyke <[email protected]>
wrote:
On 10/18/2010 09:07, Steven Schveighoffer wrote:
What case were you thinking of for requiring mutablity for equality
testing?
What about caching?
class C {
private int hashValue = -1;
// Mutators reset hashValue to -1.
int getHash() {
if (this.hashValue == -1) {
this.hashValue = longExpensiveCalculation();
}
return this.hashValue();
}
bool opEquals(C other) {
if (this.getHash() == other.getHash()) {
return slowElementwiseCompare(this, other);
} else {
return false;
}
}
}
The object's state is still changing. If you don't consider hashValue to
be part of the object's state, then that's what we call 'logical const'
(implemented in C++ via the mutable keyword). Only certain members get
such privileged status (such as the monitor object).
If you think it's worth doing, you can always cast. Despite the label of
'undefined behavior', I believe the compiler will behave fine if you do
that (it can't really optimize out const calls).
-Steve