array initialization problem

Qian Xu quian.xu at stud.tu-ilmenau.de
Fri Jan 16 13:19:46 PST 2009


Hi All,

I have accidentally written a buggy class.

Briefly described as follows:
  1. The class contains a list of string
  2. The list of string is assigned to a constant in constructor
  3. Try to change the value of the list
  4. Create another class by repeating step 1-3 again
  5. Add both of them to a LinkSeq object
  6. Print their values again
Now you will find their lists have the same values now.

Can someone explain, why the values are different before they are 
inserted into a list?
And why this.str has no problem?


The console output and the source are included below.

##################### console output begin ############################

list: [111,222,]
  str: hello
-----------------------------
list: [333,444,]
  str: world
-----------------------------
--- after insert ---
-----------------------------
list: [333,444,]
  str: hello
-----------------------------
list: [333,444,]
  str: world
-----------------------------

##################### console output end ############################

######################### code begin ############################

module test;

import tango.io.Console;
import tango.util.collection.LinkSeq;

const char[][] CLIST = [null, null];
const char[] CSTR = "hello";

class Entity
{
   char[][] list;
   char[] str;

   this()
   {
     this.list = CLIST;
     this.str = CSTR;
   }

   void print()
   {
     Cout.opCall("list: [");
     foreach (char[] s; list)
     {
       Cout.opCall(s ~ ",");
     }
     Cout.opCall("]\n");
     Cout.opCall(" str: "~this.str);
     Cout.opCall("\n-----------------------------\n");
   }
}

void main()
{
   Entity e = new Entity();
   e.list[0] = "111";
   e.list[1] = "222";
   e.str = "hello";
   e.print();

   Entity e2 = new Entity();
   e2.list[0] = "333";
   e2.list[1] = "444";
   e2.str = "world";
   e2.print();

   Cout.opCall("--- after insert ---\n-----------------------------\n");
   LinkSeq!(Entity) l = new LinkSeq!(Entity)();
   l.append(e);
   l.append(e2);

   foreach (Entity entity; l)
   {
     entity.print();
   }
}

######################### code end ############################


-- 
Xu, Qian (stanleyxu)
  http://stanleyxu2005.blogspot.com


More information about the Digitalmars-d-learn mailing list