`clear`ing a dynamic array

John Colvin via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Oct 24 07:18:02 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`.

D's arrays are not pure reference types, they work like `struct 
Array(T) { size_t length; T* ptr; }` with some extra methods and 
operators. If you think of them like that it should be clear what 
is/isn't possible.

If you want to have two references to the same array, including 
the length, use T[]* or a ref argument to a function or wrap it 
in a class.


More information about the Digitalmars-d-learn mailing list