Array slice length confusion

Steven Schveighoffer schveiguy at yahoo.com
Wed Jul 8 06:48:09 PDT 2009


On Wed, 08 Jul 2009 02:48:31 -0400, Tim Matthews <tim.matthews7 at gmail.com>  
wrote:

> Was this a design choice, bug, undefined behavior, etc...?

design choice.

A slice *is* an array in the current design.  Increasing the length may or  
may not make a copy of it.  An array slice doesn't know it was originally  
part of another array (i.e. there are no references back to the original  
array) so how would it know that there is data around it?  The only  
exception is appending to a prefix slice.  If a slice starts at the front  
of an allocated array, the runtime cannot tell that it was not the  
original array, so it clobbers data that was in the original array:

char[] str = "blah".dup;
char[] sl = str[0..1];
sl ~= "r";
assert(str == "brah");

BTW, all of this is defined behavior, see  
http://www.digitalmars.com/d/2.0/arrays.html#resize

-Steve


More information about the Digitalmars-d-learn mailing list