Array literals MUST be immutable.

Steven Schveighoffer schveiguy at yahoo.com
Thu Feb 18 13:46:05 PST 2010


On Thu, 18 Feb 2010 16:17:50 -0500, Denis Koroskin <2korden at gmail.com>  
wrote:

> On Thu, 18 Feb 2010 18:42:16 +0300, Michel Fortin
> <michel.fortin at michelf.com> wrote:
>
>>
>> Consider this case:
>>
>> 	int a, b, c;
>> 	int[] array;
>> 	array ~= [a, b, c];
>> 	array ~= toArray(a, b, c);
>>
>> Does it make sense to heap-allocate the mutable array? Hardly. With the  
>> literal, the compiler is free to optimize away the heap allocation, not  
>> so with toArray.
>>
>>
>
> [a, b, c] could result in a static array. Then there wouldn't even be a  
> need for toArray, just use more natural int[] arr = [a, b, c].dup; syntax

That would be bad,  T[] is implicitly casted from T[N].  Consider that you  
could easily escape stack data using this.  In other words, the type  
system would allow the assignment without the dup.

-Steve



More information about the Digitalmars-d mailing list