Yes, the standard library's collection types, including Array
and ArraySlice
, all have copy-on-write behaviour. This means that they can share storage of their elements with other collections until they are mutated, in which case they will take their own copy of them.
In your case, the underlying array buffer that the slice firstHalf
has a view onto is non-uniquely referenced (as both absences
& secondHalf
also have a view onto it). Therefore when you go to mutate firstHalf
, a copy is triggered – creating a new buffer containing the elements of the slice (but not necessarily the entire array).
firstHalf
now has a unique view onto this new buffer, with absences
& secondHalf
both sharing a view onto the old array buffer. Therefore firstHalf
can now mutate the elements of its buffer without affecting the elements of the original array, thus preserving value semantics.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…