Why struct opEquals must be const?
Steven Schveighoffer
schveiguy at yahoo.com
Mon Oct 18 12:51:45 PDT 2010
On Mon, 18 Oct 2010 15:43:29 -0400, Rainer Deyke <rainerd at eldwood.com>
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
More information about the Digitalmars-d
mailing list