arr.ptr, @safe and void*

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jun 15 13:33:54 PDT 2016


On 6/15/16 4:08 PM, Nick Treleaven wrote:
> On Wednesday, 15 June 2016 at 17:35:49 UTC, Steven Schveighoffer wrote:
>> On 6/15/16 6:32 AM, Nick Treleaven wrote:
>>>
>>> My question is: would returning void* instead really be unsafe, i.e. is
>>> there a way of dereferencing it in safe code? (I'm not thinking about
>>> holes in @safe, but ways by design).
>>
>> Yes. If the meaning of this expression is different in @safe vs.
>> @system, then compiler inference can affect code drastically:
>>
>> auto d = arr1.ptr - arr2.ptr;
>
> I probably wasn't clear - I'm not suggesting .ptr returns void*, I agree
> with you. But I don't get why arr.ptrValue can't be safe and return
> void* instead of uintptr_t.

It could probably do this. Dereferencing a void * isn't valid, so it 
kind of has the same effect. However, there are many functions which 
take void * and do write to/read from the data pointing at it (e.g. 
memcpy). These aren't @safe, so they should be off-limits.

The original fix proposed by Walter was to return const(void)*. This 
probably would have been fine, Daniel objected to it, but he may have 
been thrown off by the comment in the code which said "Ok because the 
user will never dereference the pointer", hinting the user may have a 
choice to do so. Hard to tell.

But the nice thing about returning a non-pointer is that you can't 
accidentally use it in cases where your code is @system or @trusted. It 
states clearly "I only care about the location of this memory, not 
what's in it". There is some value in that.

-Steve


More information about the Digitalmars-d-learn mailing list