Shouldn't casting an object to void* be considered @safe?
Joseph Rushton Wakeling
joseph.wakeling at webdrake.net
Sat Dec 14 19:16:08 UTC 2019
On Saturday, 14 December 2019 at 18:46:38 UTC, Dennis wrote:
> Whether something is useful or a good practice is not relevant
> for @safe, it is only concerned with whether it makes memory
> corruption possible.
Indeed. Has anything I said suggested otherwise?
>> And how do you validate that that usage is safe without knowing
>> something about the circumstances in which those pure
>> identities were generated?
>
> Any function that takes a void* and casts it to a different
> pointer that gets dereferenced is not @safe, whether class
> casting to void* is allowed or not. You simply can't assume
> anything about a void* even in @safe code.
Note that I said safe, not @safe. The difference matters: code
can be memory-safe, but that memory-safety may not be verifiable
by the compiler.
That's relevant to this discussion, because when asking "Should
the cast to `void*` be @safe?" we are really asking, "Is it
possible for the compiler to decide this without needing the
developer to verify?"
> Note that casting pointer types to void is already allowed in
> @safe:
You're right, I had a memory lapse on that one. Let's return the
focus to casting objects to `void*`.
I would suggest that the fact that there's a pointer under the
hood of an object is an implementation detail. An unavoidable
one, sure, but the point is that by casting it to a pointer type
of any kind (`void*` or otherwise) we are creating opportunities
for unsafe memory access that didn't exist previously.
The question of whether that cast is safe -- not @safe! -- is
down to the use-case. So it's reasonable to ask the developer to
validate both ends (i.e. how the cast to a pointer is done, and
how that `void*` is used afterwards).
> The second line could be changed to "No casting from any
> non-pointer type to a pointer type other than void*" however.
No, that won't do. What if you cast from a `ulong` to a `void*`?
The spec is correct to ban casting from non-pointer types to
pointer types. Andrej has raised a reasonable point about
whether we might reconsider where objects are concerned, but I
think the spec is correct as is (for reasons already given, and
probably others too).
More information about the Digitalmars-d
mailing list