Why is &array[0] @safer than array.ptr?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jan 25 10:12:18 PST 2017


On Wednesday, January 25, 2017 10:52:51 Kagamin via Digitalmars-d-learn 
wrote:
> On Tuesday, 24 January 2017 at 12:01:35 UTC, Jonathan M Davis
>
> wrote:
> > So, while it makes sense to say that .ptr can't be used in
> > @safe code, it really doesn't make sense to suggest &arr[0] as
> > an alternative.
>
> When you ensure pointers point to existing data, you can
> dereference them in safe code, otherwise you can't.

Fine, but in the vast majority of cases, you're calling .ptr, because you're
going to be passing the pointer to C code, in which case, doing &arr[0] buys
you very little, since the C code is inevitably going to be reading more
than that one element, and &arr[0] hasn't verified anything beyond the first
element. So, telling the programmer to use &arr[0] instead of arr.ptr is
just plain bizarre. Doing &arr[0] makes sense when you're just going to be
messing with that one element in D code, but that's pretty much it.
Otherwise, you might as well just use arr.ptr, because it's up to the
programmer to verify the @safety of what's going on at that point anyway.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list