How to detect if an array if dynamic or static
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Feb 25 11:17:11 PST 2016
On 2/24/16 9:08 PM, Adam D. Ruppe wrote:
> On Thursday, 25 February 2016 at 01:31:17 UTC, Chris Wright wrote:
>> When you get to GC-allocated stuff, there's no way to tell.
>
> The GC is easy, you can simply ask it:
>
> http://dpldocs.info/experimental-docs/core.memory.GC.addrOf.1.html
>
> "If p references memory not originally allocated by this garbage
> collector, if p is null, or if the garbage collector does not support
> this operation, null will be returned."
>
>
> The append operator uses this kind of logic to determine if it is safe
> to append. The `capacity` property on slices can query, though it is
> zero in some cases where the GC owns it, but it still needs reallocation
> to be appended to (e.g. when the array is already at the max length of
> the allocated block, or when the stomping protection kicks in. See:
> http://dlang.org/d-array-article.html )
Just a slight nit -- it will only return 0 if the array slice doesn't
end at the end of valid data as defined by the metadata. If it ends
exactly at the max length of the block, then arr.capacity == arr.length.
It will also return 0 if the memory block in question wasn't allocated
via the array allocation routine (and therefore has no metadata).
The correct answer is what you said, to use the GC to look up whether
it's part of the GC.
-Steve
More information about the Digitalmars-d-learn
mailing list