Capacity is "first-come first served" for multiple slices to all elements
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Apr 30 11:59:00 PDT 2015
(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:
import std.stdio;
void report(alias arr)()
{
writefln("%s - capacity: %s, %s",
arr.stringof, arr.capacity, arr);
}
void main()
{
// Multiple slices to all elements
auto a0 = [ 1, 2, 3, 4 ];
auto a1 = a0;
auto a2 = a0;
void reportAll()
{
report!a0;
report!a1;
report!a2;
}
reportAll();
a1 ~= 42; // <-- After this, only a1 will have capacity
reportAll();
}
The output shows that a0 an a2 lose capacity:
a0 - capacity: 7, [1, 2, 3, 4]
a1 - capacity: 7, [1, 2, 3, 4]
a2 - capacity: 7, [1, 2, 3, 4]
a0 - capacity: 0, [1, 2, 3, 4]
a1 - capacity: 7, [1, 2, 3, 4, 42]
a2 - capacity: 0, [1, 2, 3, 4]
Although I've known about the "perceived non-determinism"[1] about all
this, what is still especially surprising to me is that passing a slice
to a function can make the original slice lose capacity:
import std.stdio;
void foo(int[] arr)
{
arr ~= 42;
}
void main()
{
auto arr = [ 1, 2 ];
writefln("Before calling foo(): %s", arr.capacity);
foo(arr);
writefln("After calling foo() : %s", arr.capacity);
}
The output shows that the original variable in main() loses capacity:
Before calling foo(): 3
After calling foo() : 0
Ali
[1] http://dlang.org/d-array-article.html
More information about the Digitalmars-d-learn
mailing list