Safer casts

Janice Caron caron800 at googlemail.com
Sat May 10 01:14:07 PDT 2008


On 10/05/2008, Yigal Chripun <yigal100 at gmail.com> wrote:
>  b) Downcasts - the danger with them is that they can fail if you
>  downcast to the wrong derived class. that is why I've suggested:
> <snip>

Right. But in my view cast! (with an exclamation mark) can never fail
as such, because it's the programmer telling the compiler, "Yes, I
know you think this is wrong, but dammit I know what I'm doing, so
deal with it!". It means that the compiler makes no checks, and trusts
the programmer. (It's reinterpret_cast<T>). Therefore, it can never
return null.

But you are certainly correct in that there is a fundamental
difference between static_cast<T> and dynamic_cast<T>. The former is a
compile-time check, and the latter is a run-time check, so when the
user types

    cast(T)x;

the compiler does a compile-time check to determine whether the static
type, typeof(x), could be downcast to T, and if so, generates code
which performs a runtime check, which might return null. Although this
works, the user is never entirely sure (a) whether the compiler has
generated a straight conversion which will always succeed, or (b)
whether the compiler has generated a runtime check, which is slower,
and might fail.

For that reason, there is merit in wanting an explicit dynamic_cast<T>
equivalent. But it can't be cast!(T), because we've already used that
for reinterpret_cast<T> - a cast which performs no checks at all, not
even at compile time. Maybe we need a different syntax still for
dynamic_cast<T>. One possibility (thought I don't recommend it) is:

    cast(class T)x

The problem with that is that all the existing code which expects
cast(T)x to be a dynamic cast will still compile, give the wrong
result, and never return null. The change would introduce bugs, which
is the exact opposite of the intent. For that reason, perhaps dynamic
cast should be the default (so that existing code will still compile
and give the /right/ result), with static_cast<T> having a different
syntax.

One really, really obvious syntax for static_cast<T>(x) is

    static cast(T)x

which I think is pretty cool. It tells the compiler "I definitely want
to bypass the run-time check, but I still want the compile-time
check".


>  "cast" can be defined by the user, but I'm not sure whether it would be
>  a good idea to allow the same for "cast!"
>  what do you think?

I think that cast! should mean reinterpret_cast<T>, and therefore
always succeeds, bypassing all checks. Since it merely reinterprets
the bits, it cannot be overloadable.



More information about the Digitalmars-d mailing list