`clear`ing a dynamic array

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Oct 25 17:26:00 PDT 2015


On Sunday, October 25, 2015 16:23:14 Shriramana Sharma via Digitalmars-d-learn wrote:
> Thanks all, for your replies.
>
> Jonathan M Davis via Digitalmars-d-learn wrote:
>
> > If you want a container rather than a dynamic array - especially if you're
> > looking for full reference semantics - then use std.container.array.Array.
>
> Hmmm, pardon me but while I'm sure I don't specifically require reference
> semantics, I'm not sure how you mean to contrast a "container" vs a "dynamic
> array". Both are aware of their content count and both are iterable, no? Is
> it that by "container" you mean that something that owns its contents and is
> responsible for deleting them all when it itself is deleted?

Dynamic arrays are really pseudo-containers. They do not own or manage their
own memory, and their memory and elements are potentially shared across
multiple dynamic arrays. And mutating one dynamic array does not normally
affect another one - even if they refer to the same memory - unless you're
mutating its elements, and if one of them ends up having to be reallocated
(e.g. because there wasn't enough room to append another element when an
append operation was attempted), then two dynamic arrays which referred to
the same memory would then refer to completely different memory.

You started out this thread talking about how you wanted to be able to
"clear" a dynamic array and have that affect other dynamic arrays which
referred to the same memory, and that doesn't make any sense with a dynamic
array, because dynamic arrays are not full reference types. They share the
memory that they point to, but mutating the length of one (either directly
or by adding or removing elements) does not affect any other dynamic array
(except insofar as it can affect when an array would have to have its memory
reallocated). That's why I talked about reference semantics.

If you want a container that you pass around where removing an element from
it or adding an element to it affects all of the other variables referring
to that same data, you need an actual container type, not a dynamic array.

If you haven't read this article yet

http://dlang.org/d-array-article.html

I'd suggest that you do. The terminology that it uses does not match the
offial terminology (e.g. per the spec, T[] is a dynamic array regardless of
what memory backs it, whereas that article refers to the GC-allocated buffer
that backs most dynamic arrays as being the dynamic array), but it should
make the semantics of D's dynamic arrays much clearer.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list