toHash => pure, nothrow, const, @safe

Martin Nowak dawg at dawgfoto.de
Mon Mar 12 02:48:19 PDT 2012


> One problem I can think of is relying on the auto-inference can create
> fragile code. You make a change in one place without concentrating and
> suddenly a completely different part of your code breaks, because it's
> expecting pure, or @safe code and you have done something to prevent
> the inference. I don't know how much of a problem that could be, but
> its one I can think of.
>
> --
> James Miller

That sounds intentionally.

Say you have a struct with a getHash method.

struct Key
{
     hash_t getHash() /* inferred pure */
     {
     }
}

Say you have an Set that requires a pure opHash.

void insert(Key key) pure
{
     immutable hash = key.toHash();
}

Now if you change the implementation of Key.getHash
then maybe it can no longer be inserted into that Set.
If OTOH your set.insert were inferred pure itself, then
the impureness would escalate to the set.insert(key) caller.

It's about the same logic that would makes nothrow more useful.
You can omit it most of the times but always have the
possibility to enforce it, e.g. at a much higher level.


More information about the Digitalmars-d mailing list