The analogue of "fill-pointer" in D

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon May 18 11:52:15 PDT 2015


On 5/18/15 2:40 PM, Ali Çehreli wrote:
> On 05/18/2015 11:19 AM, John Colvin wrote:> On Monday, 18 May 2015 at
> 17:43:50 UTC, Ali Çehreli wrote:
>  >> On 05/18/2015 05:26 AM, John Colvin wrote:
>  >>> On Monday, 18 May 2015 at 11:40:13 UTC, thedeemon wrote:
>  >>>> On Monday, 18 May 2015 at 10:24:25 UTC, Dennis Ritchie wrote:
>  >>>>
>  >>>>> No, afraid not. Function capacity is not an analogue of
> fill-pointers!
>  >>>>
>  >>>> It's exactly the same.
>  >>>
>  >>> But in D capacity is affected by other things.
>  >>>
>  >>> auto a = new int[20];
>  >>> auto b = arr[0..10];
>  >>> //can't now append to b without re-allocating or using
> assumeSafeAppend.
>  >>
>  >> Perfect opportunity to inject my newly-discovered issue with capacity:
>  >>
>  >> void main()
>  >> {
>  >>     auto a = new int[20];
>  >>     foo(a);
>  >>     //can't now append to a
>  >> }
>  >>
>  >> void foo(const(int)[] p)
>  >> {
>  >>     p ~= 42;
>  >> }
>  >>
>  >> Ali
>  >
>  > I don't understand what's counterintuitive here. Slices are just pointer
>  > and length, everything else is global state.
>
> Nothing counterintuitive. I have discovered recently that when there are
> multiple slices with equal length, capacity is shared until one of them
> appends, in which case that first appender wins the capacity.
>
> I have always known about non-stomping and why this has to be so. What
> was new to me is the initial suspense when we don't know who will win
> the capacity. Just news to me.
>
> In all other cases where there is one longest slice (like your example),
> then there is only one owner of capacity.

It's no different. No slice "owns" the capacity, the runtime does. There 
can be multiple slices that access the capacity.

Also note that the longest slice doesn't necessarily have access to 
appending. All that is required is that the slice end lands on the array 
end:

int[] arr = new int()[5];
auto arr2 = arr[4..5];
arr = arr[0..3];
assert(arr.length > arr2.length);
assert(arr2.capacity);
assert(arr.capacity == 0);

It is a very difficult concept to conceptualize. I should write a pseudo 
array type to demonstrate how the array runtime code works as an object 
instead of as a collection of obtuse runtime functions.

-Steve


More information about the Digitalmars-d-learn mailing list