can we un-deprecate .ptr on arrays in @safe code? cf issue 18529

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Feb 27 12:39:04 UTC 2018


On Tuesday, February 27, 2018 04:20:38 Timothee Cour via Digitalmars-d 
wrote:
> this would be more bearable if there was a standard @trusted method to
> get array `.ptr`, eg:
> in `object.d` (so that it's indeed standard)
>
> ```
> @trusted @nogc pure nothrow
> auto pointer(T)(T a){
>   return a.ptr;
> }
> ```

Except that that's really not how @trusted is supposed to be used. The
programmer needs to verify that the caller is using a.ptr in a manner that
is actually @safe, because the compiler is not smart enough to determine
that for you. Wrapping it in an @trusted function means that the caller
won't get an error and that the programmer won't necessarily know that they
need to verify the calling code. It's the code that's using ptr that needs
to be verified, not the actual accessing of ptr.

Hiding the access to ptr within an @trusted function goes against that
entire idea of @trusted and makes it easy to use ptr without realizing that
you need to be checking the code that's using it, since you just called a
wrapper function to silence the compiler instead of listening the compiler
and studying the code using ptr to verify its @safety.

>
> again, the deprecation message is misleading because `&a[0]` isn't
> equivalent to `a.ptr`
> having something like `pointer` (and making deprecation msg use that)
> would be a better mitigation

In almost all cases, &a[0] is equivalent to a.ptr except that it does bounds
checking, so it's actually @safe and thus doesn't need to be manually
verified by the programmer, unlike your pointer function suggestion.

If you have a use case where you need a.ptr rather than &a[0], then that
just means that you're going to have to verify that your code is @safe in
spite of using an @system operation and mark it @trusted if it is. Simply
treating a.ptr as @safe when it isn't or wrapping it in an @trusted function
just defeats the purpose of the whole @safety system.

Now, maybe in some simple cases, the compiler can be improved to detect that
what you're doing with a.ptr is actually @safe and not give an error, but as
long as it can't, any use of a.ptr needs to be verified by the programmer.

- Jonathan M Davis



More information about the Digitalmars-d mailing list