Shouldn't casting an object to void* be considered @safe?

Ola Fosheim Grøstad ola.fosheim.grostad at gmail.com
Sun Dec 15 07:40:41 UTC 2019


On Saturday, 14 December 2019 at 23:48:38 UTC, Joseph Rushton 
Wakeling wrote:
>     ulong u = 8;
>     auto v = cast(void*) u;
>
> ... is totally unsafe, and the compiler rightly rejects it if 
> you try to do that in a code block marked @safe.

It is not type safe, but it is memory safe.

void has zero extent, so it will never be dereferenced without an 
unsafe action.

It is no different from having a pointer to a zero-length array, 
or a zero-length slice. Allocators will often allocate 1 byte if 
asked to allocate 0 though, to avoid such typing issues. I.e. to 
allow you to obtain unique identities with zero extent.

So it is problematic, but not because of void*. It is only 
problematic because other code is unsafe.



More information about the Digitalmars-d mailing list