Capacity is "first-come first served" for multiple slices to all elements

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Apr 30 19:49:56 PDT 2015


On Thursday, April 30, 2015 11:59:00 Ali Çehreli via Digitalmars-d-learn wrote:
> (Thanks to Luís Marques for waking me up.)
>
> Although it makes sense now, somehow some parts of this story is news to
> me after all these years. :-/
>
> When there are multiple slices to all elements of an array, they all
> start with same capacity until an element is added to one of them. After
> that, all the other slices get zero capacity:

LOL. This is the sort of thing that's pretty straightforward when you think
through how arrays work, but it seems like so few people understand it.
You'd _think_ that array slicing its associated semantics wouldn't be all
that hard to understand, but it seems like it trips most of us up from time
to time, and pretty much everyone has trouble with them initially.

I expect that part of the problem is simply the fact that it's all hidden
behind T[] rather than actually seeing something like

struct Array(T)
{
    size_t length;
    T* ptr;
}

when you're coding, since that alone makes a lot of the basic array
semantics a lot more clear, and even if the capacity situation isn't clear
at that point, at least it's clear that it's not actually part of the array
itself, which makes some of semantics that one might expect with something
like a vector clearly not work.

I'm definitely going to have to cover some of the array basics in my talk on
ranges at dconf, simply because of how much they affect ranges and how often
they're misunderstand. And I _still_ occasionally end up "Aha!" moments
occasionally when dealing with this stuff...

- Jonathan M Davis




More information about the Digitalmars-d-learn mailing list