Is [ 0, 1, 2 ] an immutable array?

Steven Schveighoffer schveiguy at yahoo.com
Wed Aug 12 08:16:24 PDT 2009


On Tue, 11 Aug 2009 19:05:56 -0400, Ali Cehreli <acehreli at yahoo.com> wrote:

> Does the expression [ 0, 1, 2 ] form an immutable array? If so, is the  
> assignment to a[0] undefined below? Is it trying to modify an immutable  
> element?
>
>     int[] a = [ 0, 1, 2 ];
>     a[0] = 42;
>
> The reason for my thinking that [ 0, 1, 2] is an array is because it has  
> the .dup property and this works too:
>
>     int[] a = [ 0, 1, 2 ].dup;
>

No, it's a mutable array.  It's one of the quirks of D2 that bugs me.  A  
string literal is an immutable array but a normal array literal actually  
allocates new space on the heap for the array every time you use it.  So  
if you assign the same literal to 2 different variables, they are 2  
separate copies of the array.

I think the behavior should be identical to strings.

I think there's even a bugzilla for that...

-Steve


More information about the Digitalmars-d-learn mailing list