Initialisation of static immutable arrays
Steven Schveighoffer
schveiguy at yahoo.com
Wed Oct 6 05:34:17 PDT 2010
On Wed, 06 Oct 2010 08:21:08 -0400, Lars T. Kyllingstad
<public at kyllingen.nospamnet> wrote:
> On Wed, 06 Oct 2010 07:39:48 -0400, Steven Schveighoffer wrote:
>> Of course. If you realize that the expression [1,2,3] is not immutable,
>> then it makes sense.
>>
>> Another example to help you think about it:
>>
>> void foo(int x)
>> {
>> immutable int[3] = [1,2,x];
>> }
>>
>> This must be run on every call of foo, because x can vary.
>
> I don't think that is a very good reason. The compiler could detect the
> special (and, might I add, common) case where an array literal whose
> contents are known at compile time is assigned to an immutable variable,
> and treat it as immutable even though [1,2,3] is formally of type int[].
I'm not saying it is a good explanation, but it is why the compiler does
it. Any time an array literal occurs anywhere is an allocation. I have
never seen a case where the compiler optimizes that out. Given that
context, the behavior makes sense.
I don't think any allocation should occur here, even if array literals are
not made immutable, because that allocation is going to be thrown away
immediately. I agree this should be special-cased. I believe there are
several bugs on array literals and allocations.
-Steve
More information about the Digitalmars-d-learn
mailing list