Safer casts

Janice Caron caron800 at googlemail.com
Fri May 9 22:59:23 PDT 2008


On 10/05/2008, Dee Girl <deegirl at noreply.com> wrote:
> But in C++ I can not grep for old-style cast. In D I can.

That still doesn't help. You can stare at a bug for ages, and still
not see it. But if the compiler tells you it's there, then you can
slap your head and say "Doh! Of course! Why didn't I see that!?"

The point being that it is way, way, /way/ better to catch bugs at
compile-time, than at run-time. Any word for "catching bugs at run
time" is "crashing". :-)

We had exactly this situation recently with

    class C {}
    C c;
    if (c == null) // now a compile-time error.

This was a run-time error for ages. ("c == anything" is translated to
"c.opEquals(anything)", which will crash if c is unassigned. But the
coder was attempting to test whether or not c was unassigned). Finally
it's a compile-time error. Moving the bug detection to compile-time
not only saved a lot of people a lot of hair-pulling out, it also
exposed many bugs in Phobos.

You can grep for "== null", but, so what? People don't. Sometimes its
hard to see your own bugs. Having the compiler tell you that they're
there is just fantastic. That's the reason for this proposal (the
latest version of which is, I think, pretty reasonable).

1) convert or downcast: cast(Foo)bar
2) reinterpret: cast!(Foo)bar
3) constancy: cast(invariant)bar, cast(!const)bar



More information about the Digitalmars-d mailing list