The great slice debate -- should slices be separated from arrays?
Phil Deets
pjdeets2 at gmail.com
Tue Nov 24 19:09:20 PST 2009
I'm somewhat new to D; so take everything I say with a grain of salt.
It seems to me that there is a tension here between high-level and
low-level. A high-level Array type might make slices be a Range. The Range
would keep a reference to the Array type plus a start and end index. When
the slice gets accessed, array range checking occurs to make sure the
array hasn't shrunk outside of the area the Range covers.
Array!(int) x = [1, 2, 3, 4, 5];
auto y = x[0..$];
x.length -= 1;
y[4] // array out of bounds error
Also, when Array reallocates, all the Range slices would remain valid
since they call .ptr to get the pointer anyway whenever they are indexed.
Maybe even appending to a Range slice would insert the elements instead of
stomp.
Array!(int) x = [1, 2, 3, 4, 5];
auto y = x[0..1];
y ~= [5, 6]; // x is [1, 5, 6, 2, 3, 4, 5];
The Range would tell the Array to insert the elements, and the Array would
take care of informing all the slices to increase their indices if they
are after the inserted data. This would require Arrays to hold weak
references to all of their slices. (I know the GC doesn't support weak
references, but I'm just speaking hypothetically.)
I think this would be perfectly safe and would avoid all the issues
presented, but the performance would suffer. This level of "fatness" would
be unacceptable for many system-level applications. So maybe int[] should
be low-level and perhaps even avoid appending altogether, while Array
would be available as a library type. But now, we are almost back to C++
with pointers and vectors. The main difference would be D's low-level
arrays store their length and can be bounds checked.
Please forgive me if someone has already proposed this. I didn't go back
and read all the past discussion before I posted this. I don't even know
what the functionality of T[new] was; so I probably don't understand all
the issues here.
More information about the Digitalmars-d
mailing list