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

Andrej Mitrovic andrej.mitrovich at
Fri Dec 13 08:05:53 UTC 2019

I recently got to thinking about a code snippet. The following 
doesn't compile, because casting to a void* is considered unsafe:

import std.stdio;

class C
     void foo() @safe
         writeln("%s:", cast(void*)this);

void main()

> test.d(7): Error: cast from `test.C` to `void*` not allowed in 
> safe code

However, I don't see this cast as being unsafe. Casting a class 
object to a `void*` doesn't break the type system by itself. You 
cannot assign a `void*` to any other pointer type without an 
additional cast, and that additional cast would be the unsafe 
one. Additionally, you cannot reference a `void*`, so as far as I 
can see it's fairly safe to use in @safe code.

Wouldn't it make sense to allow casting reference types to 
`void*` in @safe code? Are there edge-cases I haven't considered?

More information about the Digitalmars-d mailing list