On Thursday, 17 September 2015 at 19:30:09 UTC, H. S. Teoh wrote:
On Thu, Sep 17, 2015 at 06:37:04PM +0000, Stefan Koch via
Digitalmars-d wrote:
Hi,
is there any reason why opCmp and opEquals are not pure ?
I would argue it is very counter-intuitive to mutate any state
when
comparing objects.
[...]
The way I understand it, this is a historical accident: opCmp
and opEquals date back to the days before the const system was
introduced to D, so they were never originally annotated. When
the const system was introduced, a good amount of code is
already using opCmp and opEquals, and some of them may mutate
state (e.g., cache the result of previous comparisons in the
object if the comparison operation is expensive), so adding the
annotations would break existing code.
At the time, a lot of the affected code was in Phobos, where
there was a giant tangle of dependencies where changing the
const annotation on a single function would percolate to almost
half of the entire Phobos (if not more), breaking many other
seemingly-unrelated things (and introducing potential for
breakage of user code that use those things), so it was
difficult to make the transition.
Since that time, there has been talk of removing opCmp and
opEquals from Object altogether, but so far we haven't managed
to do this yet.
It's not just a question of existing code. It can be perfectly
legitimate to cache data or even to have to talk to stuff outside
your program (e.g. in a database) to check for equality, even if
that's not what the vast majority of programs should be doing.
So, requiring pure, const, @safe, or any attribute is overly
restrictive, particularly considering that D is supposed to be a
systems language. At the same time, if we don't have those
attributes on the virtual functions on Object, then folks that do
want to use those attributes are screwed (e.g. using == with
const class objects only works because of a hack in druntime
which casts away const and risks incorrect behavior). And that's
why it was decided that we really needed to remove them from
Object and just leave it up to the derived classes to declare
them and choose what attributes they would use:
https://issues.dlang.org/show_bug.cgi?id=9769
https://issues.dlang.org/show_bug.cgi?id=9770
https://issues.dlang.org/show_bug.cgi?id=9771
https://issues.dlang.org/show_bug.cgi?id=9772
Unfortunately, there are a number of technical issues in doing so
from compiler bugs to changes that need to be made in druntime
(e.g. changing the built-in AA implementation), and so while some
work has been done towards that goal, we have yet to get there.
And until we do, we're always going to have attribute problems
with any of the virtual functions on Object.
- Jonathan M Davis