On Thu, 21 May 2009 05:58:04 -0400, MLT wrote:

>> Because new elements are pre-initialized in D.
>> 
>> Just by increasing the length, you 'create' a new element (from the 'b'
>> point of view) so D initializes it.
> 
> (We were talking about something like
> int a[] = [1,2,3,4,5] ;
> b = a ;
> a ~= 6 ;
> b.length = b.length+1;)
> 
> Hmmm... yes, that has some logic to it.
> 
> D does keep track of the actual array of integers that both a and b point to

Not really. The original data is a literal so it is supposed to be
unmodifiable (I think Linux enforces it but not sure). 

> and knows when to allocate new memory for the array. 

It allocates new RAM when the current buffer allocation will not be large
enough to hold the new elements. When it does this, it allocates the new
buffer and copies the old data to it. This means that you cannot rely on
the alias 'feature' to work all the time.

For example ...

  int[] a = [ some data ];
  int[] b = a; // Ok, so both 'a' and 'b' point to the data now.

  a ~= newone; // This can't fit in so an allocation occurs
               // and the data copied, then 'a' is set to the
               // the new buffer.
  // BUT 'b' still points to the old buffer.


>So in theory it could be possible that when b.length increases,
> initialization only happens if this memory is uninitialized.

Theoreticaly yes, but it isn't going to happen.

> On the other hand, I guess that if you get an array, say b,
> in a function, you might rely on the fact that when you
> extend b.length, the area will be initialized...

This is also a trap. If the function increases the length of the array
passed to it, there will be so initialization happening, but when the
function returns, the array variable passed to the function is unchanged.
Its length is not modified so the new initialized data is not part of the
array. This is because when you pass an array to a function, it's that
small struct that is passedon the stack, so changing that will not change
the argument's properties.

eg.

  void func(int[] x)
  {
     x.length = x.length + 1;
  }
  int a[] = [1,2,3];
  func(a);
  writefln("%s", a) //--> [1,2,3] and not [1,2,3,0]

-- 
Derek Parnell
Melbourne, Australia
skype: derek.j.parnell

Reply via email to