data containers

Jarrett Billingsley kb3ctd2 at yahoo.com
Thu Jul 3 16:22:03 PDT 2008


"Moritz" <mpipahl at gspgmbh.com> wrote in message 
news:g4jm5u$1p9r$1 at digitalmars.com...
> torhu schrieb:
>> Does it work if you make this change?
>>
>> -     if(layer <= layer_count)
>> +     if(layer < layer_map.length)
>
> Well, my program DOES work, but I doesnt do what I want it to, because Im 
> now unable to insert ScreenElements into the array.
>
> Do I need to initialize the array slots before I assign an object to them? 
> The way I see it, the array has length 0 at start, and I cant put anything 
> in slot 0 or Ill get an array out of bounds error :-(

No, it's because you're using a temp variable when you shouldn't be.

ScreenElement[] single_layer = layer_map[layer];
single_layer ~= new_element;

That will get a reference the layer map at index `layer`, but when you 
concatenate, only the local single_layer will refer to the newer, longer 
array.  Just do it in place:

layer_map[layer] ~= new_element;

(Also if you don't feel like typing all those long types for variables, it's 
completely unnecessary.

auto single_layer = layer_map[layer];

Dah.)

> I guess my next problem after storing them will be to keep the garbage 
> collector from deleting them after I leave the function where the 
> ScreenElements  are created and stored into the array, or does the array 
> reference protect the ScreenElements from GC?.

Arrays are on the heap.  As long as something references said array, the GC 
won't collect objects the array holds.  That's kind of the point.  The GC 
isn't out to make your life hard; quite the opposite in fact :)

The GC is actually fairly conservative, and if it's not sure whether 
something is referenced or not (i.e. say you have some random-looking data, 
like sound data, and the GC says "hm, this looks like a pointer into an 
object"), it won't collect it. 




More information about the Digitalmars-d-learn mailing list