Why struct opEquals must be const?

Jonathan M Davis jmdavisProg at gmx.com
Sun Oct 17 00:20:14 PDT 2010


On Sunday 17 October 2010 00:02:00 Denis Koroskin wrote:
> On Sun, 17 Oct 2010 10:57:02 +0400, Nick Sabalausky <a at a.a> wrote:
> > Is there a technical reason why the l- and r- values for opEquals must be
> > const? If the restriction is purely for the intuitive notion that
> > there's no
> > heisenstructs, then I have an example I think might be worth
> > consideration:
> > lazy caching.
> > 
> > If comparison isn't always needed and requires a potentially expensive
> > computation that isn't likely needed otherwise (for example, a wrapper
> > for
> > string that does case-insensitive comparisons, if it's used in a
> > situation
> > that does more assigning/slicing/etc than comparing), then it may make
> > sense
> > to wait until an opEquals is called, and then compute the information and
> > cache it. But that requires mutating state and so can't be done in a
> > struct
> > opEquals.
> > 
> > 'Course, if there is a technical reason for the restriction, then all
> > this
> > is moot.
> 
> I don't think there any. None of the Object's methods are const (e.g.
> opEquals, toHash etc), why would struct need to be const?

They're supposed to be const. There's a long-standing bug over the fact that 
they aren't const: http://d.puremagic.com/issues/show_bug.cgi?id=1824

The fact that they aren't const is a big problem. opEquals(), toHash(), etc. 
need to work on const and immutable objects. If they don't, const and immutable 
quickly start becoming useless. And really, for const and immutable to work 
well, we really should be trying to make _more_ functions const, not fewer.

Now, I don't see any reason why we couldn't have a const and non-const version 
of functions like opEquals() and toHash() and have non-const objects use the 
non-const versions and take advantage of whatever caching facilities they might 
provide, but we _need_ to have const versions of these functions for const and 
immutable to be properly useable.

- Jonathan M Davis


More information about the Digitalmars-d mailing list