Array literals MUST be immutable.
Denis Koroskin
2korden at gmail.com
Thu Feb 18 17:47:16 PST 2010
On Fri, 19 Feb 2010 00:46:05 +0300, Steven Schveighoffer
<schveiguy at yahoo.com> wrote:
> 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
I don't think so. First of all, it is consistent with current behavior:
int[] foo()
{
int[3] staticArray = [0, 1, 2];
int[] dynamicArray = staticArray;
return dynamicArray;
}
int[] a = foo();
writeln(a); // prints garbage
Second, it's very useful to prevent unnecessary heap allocations.
I would prefer static arrays not to cast to dynamic ones implicitly, but
using opSlice syntax instead:
int[] arr = [0, 1, 2]; // error
int[] arr = [0, 1, 2][]; // fine, use on your own risk
More information about the Digitalmars-d
mailing list