A couple of questions about arrays and slices

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Jun 22 01:44:22 UTC 2023


On Wednesday, June 21, 2023 7:05:28 PM MDT Paul Backus via Digitalmars-d-learn 
wrote:
> On Thursday, 22 June 2023 at 00:10:19 UTC, Cecil Ward wrote:
> > Is .reserve()’s argument scaled by the entry size after it is
> > supplied, that is it is quoted in elements or is it in bytes?
> > I’m not sure whether the runtime has a knowledge of the element
> > type so maybe it doesn’t know anything about scale factors, not
> > sure.
>
> length, reserve, and capacity all use the same unit, which is
> elements.
>
> reserve passes a TypeInfo instance to the runtime so that it
> knows the size of the elements. You can see the implementation
> here:
>
> https://github.com/dlang/dmd/blob/v2.104.0/druntime/src/object.d#L3910

To add to that, it _has_ to know the element type, because aside from
anything related to a type's size, it bit-blits the type's init value onto
the new elements when it increases the length of the dynamic array.

You'd probably be dealing with bytes if you were explicitly asking for
memory and the like (e.g. with malloc), but a dynamic array is properly
typed, and everything you do with it in @safe code is going to deal with it
as properly typed. For it to be otherwise would require @system casts.

- Jonathan M Davis






More information about the Digitalmars-d-learn mailing list