Is this a desing rationale? (static array object member)

Regan Heath regan at netmail.co.nz
Sat Sep 29 02:48:29 PDT 2007


downs wrote:
> Brian Hsu wrote:
> [snip]
>> So a.z and b.z pointed to same array, but int [] y and int [] z are still different array instance.
>>
>> Regan mentioned that this is because the array literal [1,1,1,1,1] create only one instance of array*, so at first time I suspect that when compiler see [1,1,1,1,1], it would translate that to a fixed memory address of something like that. 
>>
> The reason is that both a.z and b.z were initialized with the _same_
> array literal, whereas y and z were initialized with _different_ array
> literals.

My understanding is that a literal gets stored in the exe when it is 
compiled/linked.

So, every literal you code exists somewhere in the exe (perhaps this 
isn't true for numeric literals but I believe it's true for strings and 
probably arrays).

Further, the compiler could choose to load the literal data into read 
only memory upon execution.

Also, the compiler might notice that one or more literals are identical 
and optimise by using the same literal loaded into the same memory for 
all X occurances in code.

So, when dealing with literals:

1. Always assume they are read-only - D 2.0 string literals are 
invariant(char) so the compiler actually reminds/enforces this.

-- perhaps there is a bug here that all array literals should be 
invariant types(1)?

2. Always copy literal data before attempting to modify it.

Regan


(1) eg.

invariant(int)[] my Literal = [0,0,0,0,0,0,0,0,0,0];

class Foo
{
   //error cannot implicitly convert 'invariant(int)' to 'int'
   //int[] myArr = [0,0,0,0,0,0,0,0,0,0];

   //so you have to say...
   int[] myArr;

   this()
   {
     myArr = myLiteral.dup;  //dup
     //OR
     myArr.length = myLiteral.length;
     myArr[] = myLiteral[];  //copy
   }
}



More information about the Digitalmars-d mailing list