digitalmars.D.learn - Shifting values within an array
- Chris Williams <aahz seanet.com> Aug 10 2010
- "Steven Schveighoffer" <schveiguy yahoo.com> Aug 10 2010
I would like to be able to do something like this:
class A {
int i;
}
int main() {
A[] list;
for (uint L = 0; L < 3; L++) {
for (uint L2 = 0; L2 < 3; L2++) {
uint index = L + L2;
uint copyAmount = list.length - index;
list.length = list.length + 1;
if (copyAmount > 0) { // Move data after index one slot later to make room
A[] sliceFrom = list[index .. (index + copyAmount)];
A[] sliceTo = list[(index + 1) .. (index + 1 + copyAmount)];
sliceTo[] = sliceFrom[];
}
list[index] = new A();
list[index].i = index;
}
}
return 0;
}
I have a running implementation which uses C's memmove(), but I gather that
this isn't a safe means to do it as the garbage collector
might run while the references to the object are being manipulated. Is there a
way to do this outside of a loop?
Aug 10 2010
On Tue, 10 Aug 2010 09:01:28 -0400, Chris Williams <aahz seanet.com> wrote:I would like to be able to do something like this: class A { int i; } int main() { A[] list; for (uint L = 0; L < 3; L++) { for (uint L2 = 0; L2 < 3; L2++) { uint index = L + L2; uint copyAmount = list.length - index; list.length = list.length + 1; if (copyAmount > 0) { // Move data after index one slot later to make room A[] sliceFrom = list[index .. (index + copyAmount)]; A[] sliceTo = list[(index + 1) .. (index + 1 + copyAmount)]; sliceTo[] = sliceFrom[]; } list[index] = new A(); list[index].i = index; } } return 0; } I have a running implementation which uses C's memmove(), but I gather that this isn't a safe means to do it as the garbage collector might run while the references to the object are being manipulated. Is there a way to do this outside of a loop?
I think memmove should be fine. All thread stacks are scanned during GC cycles, so there is no danger of having one element get collected. I think memmove will not copy half a reference anyways. -Steve
Aug 10 2010








"Steven Schveighoffer" <schveiguy yahoo.com>