Code security: "auto" / Reason for errors

Alex Parrill via Digitalmars-d digitalmars-d at puremagic.com
Wed Jun 1 14:43:01 PDT 2016


On Wednesday, 1 June 2016 at 14:52:29 UTC, John Nixon wrote:
> On Wednesday, 2 March 2016 at 21:37:56 UTC, Steven 
> Schveighoffer wrote:
>
>> Pointer copying is inherent in D. Everything is done at the 
>> "head", deep copies are never implicit. This is a C-like 
>> language, so one must expect this kind of behavior and plan 
>> for it.
>
> I sympathise with Ozan. What is the best reference you know 
> that explains this fully?

Slices/dynamic arrays are literally just a pointer (arr.ptr) and 
a length (arr.length).

Assigning a slice simply copies the ptr and length fields, 
causing the slice to refer to the entire section of data. Slicing 
(arr[1..2]) returns a new slice with the ptr and length fields 
updated.

(This also means you can slice arbitrary pointers; ex. 
`(cast(ubyte*) malloc(1024))[0..1024]` to get a slice of memory 
backed by C malloc. Very useful.)

The only magic happens when increasing the size of the array, via 
appending or setting length, which usually allocates a new array 
from the GC heap, except when D determines that it can get away 
with not doing so (i.e. when the data points somewhere in a GC 
heap and there's no data in-use after the end of the array. 
capacity also looks at GC metadata).


More information about the Digitalmars-d mailing list