Slices: Termination of Sharing

In this lesson, we will discuss the concept of termination of sharing in slices.

Slice sharing #

It is possible to access the same elements by more than one slice. For example, the first two of the eight elements below are being accessed through three slices:

Press + to interact
import std.stdio;
void main() {
int[] slice = [ 1, 3, 5, 7, 9, 11, 13, 15 ];
int[] half = slice[0 .. $ / 2];
int[] quarter = slice[0 .. $ / 4];
quarter[1] = 0; // modify through one slice
writeln(quarter);
writeln(half);
writeln(slice);
}

The effect of the modification to the second element of quarter is seen through all slices.

Making a slice longer may terminate sharing #

When viewed this way, slices provide shared access to elements. This sharing poses the question of what happens when a new element is added to one of the slices. Since multiple slices can provide access to the same elements, there may not be room to add elements to a slice without stomping on the elements of other slices of the same array.

D ...