`clear`ing a dynamic array

qsdfghjk via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Oct 24 23:16:00 PDT 2015


On Saturday, 24 October 2015 at 13:18:26 UTC, Shriramana Sharma 
wrote:
> 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`.

If you don't want to mess with pointers (as sugggested in the 
first answer) you can also use std.typecons.RefCounted:

---
import std.stdio;
import std.typecons;

RefCounted!(int[]) b;

void main()
{
   int[] a = [1,2,3,4,5];
   b = a;
   writeln(a);
   writeln(b);
   a = [];
   writeln(a);
   writeln(b);
}


More information about the Digitalmars-d-learn mailing list