Why struct opEquals must be const?

Steven Schveighoffer schveiguy at yahoo.com
Tue Oct 19 04:56:23 PDT 2010


On Mon, 18 Oct 2010 17:31:31 -0400, Rainer Deyke <rainerd at eldwood.com>  
wrote:

> On 10/18/2010 13:51, Steven Schveighoffer wrote:
>> 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?
>
>> The object's state is still changing.
>
> Yes, that's my point.  D doesn't have "logical const" like C++, so not
> all logically const operations can be declared const.  opEquals is
> always logically const, but it cannot always be physically const.

Then you cannot call opEquals with a const or immutable object.  To say  
you're not allowed to compare const or immutable objects is pretty limited.

>> 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).
>
> Not safe.  The set of const objects includes immutable objects, and
> immutable objects can be accessed from multiple threads at the same
> time, but caching is not (by default) thread-safe.

You have to take steps to make sure it is.  IMO, your code actually is  
thread safe because overwriting an int with the same int will not result  
in any races.

-Steve


More information about the Digitalmars-d mailing list