Why is &array[0] @safer than array.ptr?
    Rene Zwanenburg via Digitalmars-d-learn 
    digitalmars-d-learn at puremagic.com
       
    Tue Jan 24 03:50:16 PST 2017
    
    
  
On Tuesday, 24 January 2017 at 11:38:16 UTC, Jonathan M Davis 
wrote:
> Likely because it does bounds checking, so you at least know 
> that it's not null. But I don't see why that would really 
> improve much considering that the odds are that you're really 
> going to be accessing far more than just the first element with 
> the pointer. It seems _slightly_ better from a safety 
> perspective but only slightly. So, I don't know what the point 
> is in suggesting it as an alternative.
>
> - Jonathan M Davis
Pointer arithmetic is forbidden in @safe code so that's not a 
problem. The reason this was introduced was indeed bounds 
checking. For example:
@safe:
int parse(ref char[] input)
{
   // Pop all numeric characters from the front of the input slice 
and convert to int
}
void main()
{
   auto input = "123".dup;
   parse(input);
   // Since all numeric chars have been popped, input is now 
effectively input[$ .. $].
   // This means input.ptr is pointing past the end of the array.
   writeln(input.ptr); // Out of bounds access
}
    
    
More information about the Digitalmars-d-learn
mailing list