Diffrent instance of class share static array member?
Brian Hsu
brianhsu.hsu at gmail.com
Fri Sep 28 08:07:43 PDT 2007
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?
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?
--
Brian Hsu
-------------- next part --------------
A non-text attachment was scrubbed...
Name: test.d
Type: application/octet-stream
Size: 543 bytes
Desc: not available
Url : http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20070928/f2d43653/attachment.obj
More information about the Digitalmars-d-learn
mailing list