safer casts - take II

Janice Caron caron800 at googlemail.com
Tue May 13 09:10:59 PDT 2008


On 13/05/2008, BCS <ao at pathlink.com> wrote:
>  looks good. Excluding the Const stuff (and I've been ignoring all that for
> months) it seems consistent and reasonably compact. As for the Const stuff,
> I'll let others pass jugment.

Obviously, since I was partly involved in drafting this, I support it.

Basically what this means is that, once the change is made, 99% of
your code will compile, and maybe 1% wont. (I'm making these numbers
up, by the way, just for illustration).

So you look at the lines the don't compile, and ponder "Is this a bug,
or is it correct?". If you decide it's correct, you change "cast" to
"cast!" and recompile, and all should be well.

If it /still/ doesn't compile, it's almost certainly a bug in your
code. But not neccesarily, because there's still a chance you /might/
be doing two things at once, in which case, if you're really, really
sure it's not a bug, you change your code from "cast!(T)" to
"cast!(T)cast(U)", where U is some intermediate type (so the safe cast
changes the type but not the constancy, and then the danger cast then
changes the constancy). Now it should compile.

And if it /still/ doesn't compile, it's either a bug or very badly
designed code. In the latter case, you can use reinterpret_cast!(T) to
force the line to compile.

Simply put - this is a tool for finding bugs at compile time. Without
this, those bugs could bring your program crashing down at run time.
So yes, I love this idea.



More information about the Digitalmars-d mailing list