Safe cast of arrays
Steven Schveighoffer via Digitalmars-d
digitalmars-d at puremagic.com
Fri Feb 12 11:32:32 PST 2016
On 2/12/16 12:15 PM, Chris Wright wrote:
> Casting between primitive value types (eg long -> int) is @safe. You
> can't get memory errors that way, and the conversions are well-defined.
>
> Casting between object references is @safe (assuming the object
> references are valid; @safe doesn't protect you from dereferencing an
> invalid pointer you got from @system code). You can dereference null that
> way, but that's allowed by design.
All good points.
what I'm trying to say safe shouldn't allow is reinterpret casting.
i.e.: *cast(T*)(&x)
So casting IMO shouldn't be allowed unless it invokes some kind of
handler that ensures the conversion is safe.
I'd include in this list:
a) casting between object types
b) casting builtin types that are not, or do not contain, references
(that are defined by the compiler)
c) casting an aggregate that has a matching opCast
> If you wanted to restrict casts between array types, that would be more
> reasonable, but some work has already gone into making those casts safe
> (eg long[] -> int[]). It would also prevent @safe memory-mapped IO, even
> if we provided a wrapper that yielded a ubyte[].
Casting an array involves casting a pointer with a reinterpret style
cast. IMO, the language is better off requiring a @trusted escape for
such things.
>
> If you're just talking about casting from void[] in @safe code, that's
> reasonable, but a little more restrictive than necessary. Casting *to*
> void[] in this scenario is safe, just not generally useful -- you
> wouldn't be able to cast back in @safe code.
casting to void[] doesn't require a cast. So I think it should be fine
in @safe code.
-Steve
More information about the Digitalmars-d
mailing list