`clear`ing a dynamic array
Shriramana Sharma via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Oct 24 06:18:18 PDT 2015
Hello. I had first expected that dynamic arrays (slices) would provide a
`.clear()` method but they don't seem to. Obviously I can always effectively
clear an array by assigning an empty array to it, but this has unwanted
consequences that `[]` actually seems to allocate a new dynamic array and
any other identifiers initially pointing to the same array will still show
the old contents and thus it would no longer test true for `is` with this
array. See the following code:
import std.stdio;
void main()
{
int a[] = [1,2,3,4,5];
int b[] = a;
writeln(a);
writeln(b);
//a.clear();
a = [];
writeln(a);
writeln(b);
}
which outputs:
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[]
[1, 2, 3, 4, 5]
How to make it so that after clearing `a`, `b` will also point to the same
empty array? IOW the desired output is:
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[]
[]
... and any further items added to `a` should also reflect in `b`.
--
Shriramana Sharma, Penguin #395953
More information about the Digitalmars-d-learn
mailing list