back to arays

Oskar Linde oskar.lindeREM at OVEgmail.com
Mon May 15 01:48:16 PDT 2006


Max Samuha skrev:
> I thought array references are similar to object references like in C#
> (actually, thay are object references in C#) and that was my mistake:
> 
> int[] a = new int[20];
> int[] b = a;
> 
> a.length = 40; // a is copied and b is not updated to point to a's
> data;
> 
> Does it mean that anytime i change an array, i have to manually update
> all references to it or should i wrap my array in an Array class so
> that all references to any instance of that array remain valid?
> 
> If the question have been already discussed please refer me to the
> right thread. Thanks

The behavior of D's built in arrays have been the cause of much confusion.

D's arrays actually have a kind of schizophrenic nature. They are value 
types referring to some portion of memory, and as such, they are not 
pure arrays (of course a matter of interpretation), but rather array 
slices. On the other hand they support append operations, and 
automatically copy and reallocate the data when the length is increased, 
which doesn't make sense for a pure slice type.

So in the sense of being arrays, D's arrays neither fulfill the expected 
semantics of being a value type nor a reference type.

This will probably make many D users cringe, by my suggestion is to use 
an array wrapper type with reference semantics. Something like this: 
(untested and incomplete code)

class Array(T) {
	T[] data;
	this() {}
	this(int n) { length(n); }
	this(T[] data) { this.data = data; }
	void length(size_t n) { data.length = n; }
	size_t length() { return data.length; }
	Array dup() { return new Array(data.dup); }
	T opIndex(size_t i) { return data[i]; }
	T opIndexAssign(T v, size_t i) { return data[i] = v; }
	T[] opSlice(size_t a, size_t b) { return data[a..b]; }
	int opApply(...) {...}
}	

Usage:
Array!(int) a = new Array!(int)(20);
Array!(int) b = a;

a.length = 40; // a is NOT copied and b is updated to point to a's data

Properly implemented this will work as you expect with one caveat. There 
is no reference return type for opIndex, making arrays of structs 
somewhat inconvenient.

I think you can find a proper implementation in the ancient DTL library.


Regards,

Oskar



More information about the Digitalmars-d-learn mailing list