Array id is

I am having trouble understanding the array ID in D.

Object s = null; // or new Object
auto a = [s];
auto b = [s];
writeln(a is b); // > false
writeln(a == b); // > true

      

Will print false

, then true

. I have no problem with ==

, but the D2 ref states that

For static and dynamic arrays, identification is defined as referring to the same array elements and the same number of elements.

This is contrary to the behavior I am experiencing. a

and b

both have one element, which is s

is why they must be the same. Am I misinterpreting something?

Edit: I was wrong in assuming that the same array elements meant they were comparing equal over is

, which are the identity comparison models in D.

+3


source to share


1 answer


In D, an array is a tuple of pointer and length. Arrays are identical if they are the same length and point to the same array. They are equal if the contents of what they point to are the same.

In your example, a

both b

are equal, but not identical because they do not point to the same array. If they do, the change will change a[0]

as well b[0]

, but it doesn't.

If you had:

Object s = null;
auto a = [s];
auto b = a;
writeln(a is b); // > true
writeln(a == b); // > true

      

Then they both will be true because they both refer to the same array. Also, in this case, the change a[0]

will also change b[0]

.



The key misunderstanding here is that the elements of an array are not the same for every array, they simply refer to the same elements:

            s
            ^
            |
       +----+----+
       |         |
      [0]       [0]
       ^         ^
       |         |
       a         b

      

If they were the same, you would have something like this:

            s
            ^
            |
           [0]
            ^
            |
       +----+----+
       |         |
       a         b

      

There are several levels of indirection here, which is probably causing the confusion.

+7


source







All Articles