deep copy or shallow copy?

Ali Çehreli acehreli at yahoo.com
Fri Dec 9 12:32:37 PST 2011


On 12/08/2011 12:52 PM, Timon Gehr wrote:
 > On 12/08/2011 09:50 PM, RenatoL wrote:
 >> snippet 1)
 >> auto arr1 = [1,2,3];
 >> auto arr2 = arr1;
 >> arr1[1] = 22;
 >> arr2[2] = 33;
 >> foreach (i; 0..arr1.length) write(arr1[i], " ");
 >> writeln();
 >> foreach (i; 0..arr2.length) write(arr2[i], " ");
 >>
 >> output:
 >> 1 22 33
 >> 1 22 33
 >> OK
 >>
 >> snippet 2)
 >>
 >> int[3] arr1 = [1,2,3];
 >> int[3] arr2 = arr1;
 >> arr1[1] = 22;
 >> arr2[2] = 33;
 >> foreach (i; 0..arr1.length) write(arr1[i], " ");
 >> writeln();
 >> foreach (i; 0..arr2.length) write(arr2[i], " ");
 >>
 >> output:
 >>
 >> 1 22 3
 >> 1 2 33
 >>
 >> that's unclear to me... i "agree" with the behaviour of the
 >> dynamic array... but if we have a static array we have a deep copy?
 >
 > Both copies are 'shallow', but static arrays are value types.

'shallow' would be misleading for a fixed-length (static) array because 
there is nothing else but the elements for fixed-length arrays:

void main()
{
     int[3] a;
     assert(cast(void*)&a == cast(void*)&a[0]);
}

Fixed-length array storage is similar to C arrays. These are different:

- they don't decay to a 'pointer to first element' when passed to 
functions (being value types, the whole array is copied)

- a.length is a convenience, equivalent to a.sizeof / a[0].sizeof

So it is impossible to do anything shallow with them unless we 
explicitly maintain a pointer to a fixed-length array ourselves.

Ali



More information about the Digitalmars-d-learn mailing list