Shouldn't casting an object to void* be considered @safe?
pjmlp at progtools.org
Fri Dec 13 08:24:03 UTC 2019
On Friday, 13 December 2019 at 08:05:53 UTC, Andrej Mitrovic
> I recently got to thinking about a code snippet. The following
> doesn't compile, because casting to a void* is considered
> 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
Your example is only safe if writeln happens to be safe.
If it is not implemented in D, or it is available as binary only
implementation, everything goes.
Naturally you could argue that those implementations can as well,
change the bit representation after getting the safe reference to
C, however this is another defense barrier to prevent doing the
wrong thing by default.
More information about the Digitalmars-d