Why struct opEquals must be const?

Steven Schveighoffer schveiguy at yahoo.com
Mon Oct 18 08:07:57 PDT 2010


On Mon, 18 Oct 2010 10:49:25 -0400, Pelle <pelle.mansson at gmail.com> wrote:

> On 10/18/2010 02:41 PM, Steven Schveighoffer wrote:
>> On Sun, 17 Oct 2010 02: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.
>>
>> http://d.puremagic.com/issues/show_bug.cgi?id=3659
>>
>> -Steve
>
> Shouldn't the compiler make the opEquals non-const if one of the struct  
> members requires mutability for equality testing? Just a thought.

IMO, opEquals should allow non-const, but only if the type is a value type  
(no references).  This means opEquals on a class should always be const.

Allowing opEquals to modify the original object violates the expectation  
of opEquals -- you don't expect comparison to change the objects being  
compared.

But logically, opEquals shouldn't require any specific signature -- it's  
just another function.

What case were you thinking of for requiring mutablity for equality  
testing?

-Steve


More information about the Digitalmars-d mailing list