Empty array and AA literals
monarch_dodra
monarchdodra at gmail.com
Sun Apr 6 02:52:03 PDT 2014
On Sunday, 6 April 2014 at 03:17:25 UTC, dnspies wrote:
> What's the syntax for a new empty dynamic array or associative
> array?
>
> Every time I want to set a AA, I have to say:
> (supposing I already have some variable int[int] aa which
> points to the wrong one)
>
> int[int] throwaway;
> aa = throwaway;
>
> What about for a normal dynamic array?
AA's and Dynamic Arrays are different beasts.
An Dynamic Array is merelly a "fat pointer" that holds both
pointer and length. There is no need to create or new a Dynamic
Array.
An AA, on the other hand, is completely different. It's a pointer
to an implementation, and the implementation does the actual work.
The AA lazily initializes on the first operations. However, until
initialized, an AA is pretty much just a null pointer. This can
lead to interesting scenarios such as:
//----
int[int] a; //null
int[int] b = a; //both null
assert(a is b); //They are both null
a[1] = 1; //a gets initialized
assert(a !is b); //but b remains null.
int[int] c = a; //c points to the same implementation
a[2] = 2; //a's implementation is changed
assert(a is c); //and c "sees" it.
//----
> Is there a way to say something like:
>
> aa = new int[int] ?
>
> like I would with a class.
Currently, no. However, you can force initialization with a dummy
insertion:
int[int] b = [1:1]; b.remove(1);
//b is now an empty, but initialized, AA
It's a bit dirty, but that's how it is.
More information about the Digitalmars-d-learn
mailing list