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

Steven Schveighoffer schveiguy at gmail.com
Mon Dec 16 17:01:03 UTC 2019


On 12/13/19 3:05 AM, Andrej Mitrovic wrote:
> 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: C.foo()", 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?
> 

Yes. Implicit casting to void * from another pointer type is allowed. 
i.e. this code compiles in safe mode:

int *p = new int;
void *v = p;

Class references are no different than pointers in safe code 
(rebindable, can be null, no pointer arithmetic), and they are even more 
likely to live on the heap, which makes them even safer than the above.

Please file an issue if not one already.

-Steve


More information about the Digitalmars-d mailing list