Keep in mind that
a += b;
is actually just a shorthand for
a = a + b;
So, nothing is done to the array previously referenced by a. All that happens is that the variable a is rebound to a new value, which is the result of the computation a+b. Of course, this computation should not alter the old array either, if there are references to it.
This is different from
a[0] = x;
which modifies the contents of the array referenced by a. Since arrays are reference types, this will also affect other references to the same object.
The difference is made clear from the following example:
mixed foo() { return a; }
void bar() { foo()[0] = x; // Ok, modifies the array referenced by a foo() = foo() + b; // Not ok. The "resized" array can be computed, // but not assigned back to a (or any other // variables referencing the same array) }
As for things happening on the C level, the computation a+b actualy _does_ modify the array referenced by a destructively, _iff_ there are no additional references to it. Thus you can get efficient resizing of arrays, even while maintaining the semantics described above.
If you want multiple references to an array which changes size, this can be accomplished by wrapping the array in another reference type, such as an object. Since the object will contain the only reference to the array, it can be resized efficiently, and all code which holds a reference to the object will be able to access the new array.
If one really wanted, it would be possible to make a function that destructively resizes an array regardless of the number of references (just as there are functions like m_delete() which destructively modifies mappings), however there is at least one thing which would have to be changed in the implementation in that case: Currently the empty array ({}) is shared since it is immutable. If one were able to alter the empty array in any way it would have to be instantiated anew for each time ({}) occurs in code. Apart from increased memory and time overhead, this would also create a backwards incompatibility on the C level.
/ Marcus Comstedt (ACROSS) (Hail Ilpalazzo!)
Previous text:
2004-09-10 02:14: Subject: Re: growing arrays (was: array.c)
yes, so it appears. but is that a sideeffect of something happening on the c-level that would be costly to change, or is it simply a design decision that could be changed codewise. (i am aware that this would probably break compatibility)
greetings, martin.
/ Brevbäraren