Diffrent instance of class share static array member?

Regan Heath regan at netmail.co.nz
Fri Sep 28 08:25:11 PDT 2007


Brian Hsu wrote:
> Hello, everybody
> 
> When I tried to program an knight problem, I use a loop to test every
> case, but only the answer of first case is correct. After print some
> variable, I suspect it is caused by static array member.
> 
> So I wrote a simplest code to test, it looks like following (full
> code is in the attachment), I found that every instance seems share
> the same array even another instance changed the elements in array.
> 
> class TestArray { int [] x = [0,0,0,0,0]; void doSomething () { //
> Increase every element in array by 1} }
> 
> void main () { for (int i = 0; i < 5; i++) { TestArray t = new
> TestArray(); t.doSomething(); // Print array. } }
> 
> I tried gdc/dmd at Linux/Windows all have same result, so I wondered
> is this a design rationale for memory space and efficiency?

Not sure.  It appears the array literal:

[0,0,0,0,0,0,0,0,0,0]

creates a single array of int's in memory and the assignment:

int[] x = [0,0,0,0,0,0,0,0,0,0];

causes the array reference 'x' to refer to that signle instance in all 
class instances.

Whereas what you actually want/expect is for the assignment to create a 
new array in memory and copy the contents of the literal.

> Currently I use add an constructor and in the constructor do x =
> x.dup in order to create an whole new dynamic array which only belong
> to specific instance, is my method correctly?

It works.

Regan


More information about the Digitalmars-d-learn mailing list