data containers

Koroskin Denis 2korden at gmail.com
Fri Jul 4 07:18:31 PDT 2008


On Fri, 04 Jul 2008 17:40:12 +0400, Steven Schveighoffer  
<schveiguy at yahoo.com> wrote:

> "Koroskin Denis" wrote
>> On Fri, 04 Jul 2008 03:22:03 +0400, Jarrett Billingsley
>>> "Moritz" wrote
>>>> 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.
>>>
>>>
>>
>> Or, better, use:
>> auto single_layer = layer in layer_map;
>>
>> to avoid lookup on insertion:
>> layer_map[layer] ~= new_element; ->
>> right?
>
> According to an earlier post, layer_map is a 2D array, not an associative
> array.  I think 'in' only works on AA's.
>
> What you could do though is:
>
> auto single_layer = &layer_map[layer];
>
> But I'm not sure ~ works on an array pointer, but D does do some magical
> stuff with operators when dealing with pointers, so it could work :)
>
> -Steve
>
>

You are right. It should be
*single_layer ~= new_element;

And yes, `in` doesn't work for dynamic arrays, although it could (for  
consistency and generality).


More information about the Digitalmars-d-learn mailing list