Safe cast of arrays

Chris Wright via Digitalmars-d digitalmars-d at puremagic.com
Fri Feb 12 09:15:34 PST 2016


On Fri, 12 Feb 2016 08:45:54 -0500, Steven Schveighoffer wrote:

> A cast to const may be viable.

Touché.

> However, I think casting in safe code is
> probably not something to allow.

*All* casting?

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.

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[].

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.


More information about the Digitalmars-d mailing list