Safer casts

Yigal Chripun yigal100 at gmail.com
Sat May 10 02:24:35 PDT 2008


I do not agree with the premise that a reinterpret cast always succeeds,
even the C++ version can throw an exception!

maybe, my use of the word "fail" was not accurate. let me re-phrase my
thoughts:
there are only two ways to coerce one type into another:
a) you convert the value (i.e you change the underlying memory) - this
should always produce the expected result [I mark this with cast(T)]
b) you do _not_ convert the value, you just change the type tag attached
to the value - this can produce bad results which do not conform to the
underlying memory scheme of the type. [I mark this with cast!(T)]
let's look at an example of the latter:
int a = ...;
auto c = cast!(dchar) a;

suppose the bit layout of a is illegal utf-32 encoding. would you prefer
D allowed storing such an illegal value in a dchar?
IMO, a strongly typed language (like D) must enforce at all times that
its variables are valid. I do not want D to allow storing illegal values
like that. that must be an error.

Am I making any sense?

--Yigal



More information about the Digitalmars-d mailing list