Array literals MUST be immutable.
Don
nospam at nospam.com
Thu Feb 18 12:40:45 PST 2010
Michel Fortin wrote:
>>> But assigning a literal to an immutable array should be easy to
>>> special-case in the compiler so that it doesn't do an unnecessary copy.
>>
>> Yes, but that doesn't work in the general case. It cannot be done for
>> anonymous literals.
>
> I'm not sure what you mean by "anonymous literals". Aren't all literals
> anonymous?
No. If they are function parameters, they are anonymous.
foo([1,2,3]);
As opposed to:
immutable int [] x = [1,2,3];
where they have a name, a storage class, and a chance to put an
'immutable' in.
>> Also you can't force an array literal to be CTFEd.
>
> I think that's a more general problem with CTFE. But you can force CTFE
> using an enum:
>
> enum value = ctfeFunction();
Unfortunately, that doesn't work.
(1) Enum arrays aren't stored in the executable. You can't index them.
(currently you can due, to a compiler bug, and it generates wrong code).
(2) Using 'enum' doesn't work for the anonymous case.
>
> Wrap that in a template if you want more convenience:
>
> template ctfe(alias ctfeValue) {
> enum ctfe = ctfeValue;
> }
Expressions can be aliased. So I doubt that will work.
> auto variable = ctfe!(ctfeFunction());
>
>
>>> Also, they're quite useful. How would you write the code above
>>> without them?
>>>
>>> int[] array;
>>> array.length = 3;
>>> array[0] = x;
>>> array[1] = y;
>>> array[2] = z;
>>
>> Including the library implementation:
>>
>> T[] toArray(T)(T[] values...)
>> {
>> return values.dup;
>> }
>>
>> int[] array = toArray(x,y,z);
>>
>> Mutable array literals achieve almost nothing.
>
> But now, how can the compiler optimize this and stack-allocate your
> array when it detect doesn't escape your function?
That's *exactly* the way it works now. Really, there's no difference.
The toArray function is just a single return statement, so it gets
inlined perfectly. And .dup is a compiler built-in. So it's easy for the
compiler. The compiler sees:
int [] array = [x, y, z].dup; (where [x, y, z] is the existing mutable
array syntax).
More information about the Digitalmars-d
mailing list