Initialisation of static immutable arrays

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Wed Oct 6 05:21:08 PDT 2010


On Wed, 06 Oct 2010 07:39:48 -0400, Steven Schveighoffer wrote:

> On Wed, 06 Oct 2010 06:16:45 -0400, Lars T. Kyllingstad
> <public at kyllingen.nospamnet> wrote:
> 
> [...]
> 
>> Secondly, if the above is not true, how can I verify that the array in
>> the following piece of code isn't allocated and/or copied anew every
>> time the program runs, or even worse, every time foo() is called?
>>
>>   void foo()
>>   {
>>       static immutable int[3] = [1, 2, 3];
>>   }
> 
> Actually, static probably will prevent it from being created every time
> foo is called.  I don't think there's a way to prevent it from being
> created every time the program is run.

Does anyone know a way to verify this?  (If it is in fact created every 
time the function runs, I'll change it to a module-level array 
initialised in a 'static this()' instead.)


>> I know, RTFAsm, but some help with that would be appreciated. ;)
>>
>> Thirdly, intuition tells me that when the array is immutable, the
>> 'static' shouldn't have an effect.  But experiments (i.e. printing the
>> adress of the array) indicate that it does.  Is there some reason for
>> this, or is it just a shortcoming of the compiler?
> 
> 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[].


> BTW, I'm all for making array literals immutable.  You can always make
> runtime-allocated arrays via a library function.

I completely agree.

-Lars


More information about the Digitalmars-d-learn mailing list