The program starts with a dynamic slice of odd integers 1 thru 15.
Append 17 and reassign to slice.
Declare dynamic slice tailSlice of the second half of slice.
Check the length of tailSlice, which is 5; and capacity of tailSlice, which is 7.
Since capacity > length, we ought to be able to add two integers to tailSlice without terminating sharing of slices with slice.
But incrementing the length of tailSlice by 1 breaks sharing.
This is unexpected.
Am I missing something, or have I (unlikely) found a bug in the D compiler?
What is the explanation of this behavior?
I would expect that increasing the length of tailSlice ought to continue to have sharing with slice.
source/app.d
import std.stdio;
void main()
{
int[] slice = [1, 3, 5, 7, 9, 11, 13, 15];
slice = slice ~ 17;
writeln("slice: ", slice, " length: ", slice.length, " capacity: ", slice.capacity);
writeln();
int[] tailSlice = slice[$ / 2 .. $];
writeln("slice: ", slice, " length: ", slice.length, " capacity: ", slice.capacity);
writeln("tailSlice: ", tailSlice, " length: ", tailSlice.length, " capacity: ", tailSlice.capacity, " &tailSlice[0]: ", &tailSlice[0]);
tailSlice.length += 1; // fails here
// tailSlice ~= 0; // also fails
writeln("tailSlice after incrementing length by 1: ", tailSlice, " length: ", tailSlice.length, " capacity: ", tailSlice.capacity, " &tailSlice[0]: ", &tailSlice[0]);
tailSlice[0] = 888;
writeln("After tail slice length increase and changing tailSlice[0] to 888. ", " length: ", tailSlice.length, " capacity: ", tailSlice.capacity);
writeln("tailSlice: ", tailSlice);
writeln("slice : ", slice);
}
Console output:
slice: [1, 3, 5, 7, 9, 11, 13, 15, 17] length: 9 capacity: 11
slice: [1, 3, 5, 7, 9, 11, 13, 15, 17] length: 9 capacity: 11
tailSlice: [9, 11, 13, 15, 17] length: 5 capacity: 7 &tailSlice[0]: 26AAAA31040
tailSlice after incrementing length by 1: [9, 11, 13, 15, 17, 0] length: 6 capacity: 11 &tailSlice[0]: 26AAAA31060
After tail slice length increase and changing tailSlice[0] to 888. length: 6 capacity: 11
tailSlice: [888, 11, 13, 15, 17, 0]
slice : [1, 3, 5, 7, 9, 11, 13, 15, 17]
Permalink
Reply