The analogue of "fill-pointer" in D

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


On 5/18/15 1:43 PM, 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

Well, sure you can :)

a ~= 5; // works fine

But I understand you mean that an append to 'a' will reallocate

> }
>
> void foo(const(int)[] p)
> {
>      p ~= 42;
> }
>

Not an issue, intended behavior.

For instance if foo did this:

p ~= 42;
someGlobal = p;

Now, if you didn't prevent appending a from stomping on memory, then 
someGlobal would be stomped.

BTW, the way to prevent this is to do something like:

a) dup p on append
b) const x = p; scope(exit) x.assumeSafeAppend();

Hm... an interesting wrapper type would be an 'always reallocating' 
slice type. It would have an extra boolean to indicate it must realloc 
upon append (which would then clear after the first append).

-Steve


More information about the Digitalmars-d-learn mailing list