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

Brian Hsu brianhsu.hsu at gmail.com
Mon Oct 1 08:57:02 PDT 2007


Steven Schveighoffer Wrote:

> If you examine the difference between this and the Java syntax, there lies 
> your problem:
> 
> class Test
> {
>    int[] z = new int[] {1,1,1,1,1};
>    ...
> }
> 
> notice the new keyword.  This means you are making a new array.
> 

It's valid when initial object member array in class using just array literal in Java (C++ seems forbid this, sorry that I'm wrong before).

Following is an correct Java programing which does not have same problem, so the behavior of D is a little bit strange for me before.

public class Test
{
    int [] x = {1,1,1,1,1};

    public void addByOne ()
    {
        for (int i = 0; i < x.length; i++) {
            x[i]++;
        }
    }

    public static void main (String [] args)
    {
        Test a = new Test();
        Test b = new Test();

        a.addByOne ();

        System.out.println ("b[0]:" + b.x[0]);
    }
}

But now I could understand why this happened, and I think array literal should mark as invariant(T) [] in future compiler as others said. 

Then it should be able to avoid this problem for others who using Java as their programming language and want to learn D.



More information about the Digitalmars-d mailing list