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

janderson askme at me.com
Sat Sep 29 17:53:31 PDT 2007


Brian Hsu wrote:
> I posted a similar post at D.learn newsgroup and got a explanation about this. But I have a question after got that answer: is this reasonable? 
> 
> Here is my code:
> 
> class Test
> {
>     int [] z = [1,1,1,1,1];
>     void addByOne () { //Increase all elements in x by 1}
> }
> 
> void fun1 (int y)
> {
>     int [] x = [1,1,1,1,1];
>     foreach (int i, int v; x ) {
>         x[i] = x[i]+y;
>     }
> }
> 
> void fun2 ()
> {
>     int [] y = [1,1,1,1,1];
> 
>     foreach (int i, int v; y ) {
>         Stdout.format ("{} ", v);
>     }
> 
>     Stdout.newline;
> }
> 
> void main ()
> {
>     Test a = new Test();
>     Test b = new Test();
>     a.addByOne(); 
>     // Now b.z will be [2,2,2,2,2]
>     
>     fun1(3);
>     fun2(); // Still print [1,1,1,1,1]
> }
> 
> 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. 
> 
> * http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D.learn&article_id=9580
> 
> But it clearly that int [] x and int [] y is still a different array instance even they have same array literal initialization.  
> 
> So, after all, when is a.z and b.z point to same array instance exactly? Since I believe it should be runtime, not compile time to do initialization of object member, then why a.z and b.z is same array instance but int [] x and int [] y is different array instance? 
> 
> Finally, is this behavior reasonable? Since I didn't declare that int [] as a static class member, even though they have same initialization array literal, but I would expect that a.z/b.z they should be different array have same content. (As in Java or C++)
> 
> Or is there special reasons of this strange behaver?   

Maybe D should do a kinda lazy .dup in these situations.  That is, 
sections like [1,1,1,1,1] would be marked as const somehow in the GC (or 
somewhere).  If a modification occurs it would make a call to dup the 
first time.




More information about the Digitalmars-d mailing list