A slice can lose capacity simply by calling a function

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat May 2 01:56:43 PDT 2015


On Saturday, May 02, 2015 01:21:14 Ali Çehreli via Digitalmars-d-learn wrote:
>    2)  void foo(    const(int[]) arr);  // cannot affect anything
>                                         // (even capacity)

Actually, you can modify the capacity of arr quite easily. All you have to
do is slice it and append to the slice, e.g.

auto arr2 = arr;
arr2 ~= 7;

Any code which has access to a dynamic array can affect that array's
capacity unless the array's capacity is already at its length or 0, because
if you have access to the array, you can slice, and that slice will have
access to exactly the same memory as the original. const prevents altering
the elements, of course, but it has no effect whatsoever on the ability of
other slices to expand into the memory beyond the end of that array.

And of course, if you misuse something like assumeSafeAppend (i.e. when it's
_not_ actually safe to append), then you can _really_ bork things.

Really, if you're dealing with a thread-local, dynamic array, and you check
its capacity immediately before doing something, then you can be sure that
it's capacity will be what it was when that something starts, but unless you
follow every line of code after checking the capacity and verify that none
of it could possibly have appended to a slice which referred to the last
point used in the memory block that that array points to or done something
like call assumeSafeAppend or anything else which could have affected the
capacity of that array, then you have to assume that it's possible that the
capacity of the array has changed.

I really don't think that it's reasonable in the general case to expect to
be able to guarantee that the capacity of a dynamic array won't change. If
you know exactly what the code is up to, and the array or any other array
that might refer to that same block of memory is only going to be appended
to under very controlled circumstances that you fully understand, then you
can know that the array's capacity won't change. But in general, if there's
any possibility of an array being appended to, then all bets are off.

- Jonathan M Davis




More information about the Digitalmars-d-learn mailing list