lame question

Graham Fawcett fawcett at uwindsor.ca
Mon Apr 18 10:25:56 PDT 2011


On Mon, 18 Apr 2011 11:38:56 -0400, Steven Schveighoffer wrote:

> On Mon, 18 Apr 2011 11:21:46 -0400, Graham Fawcett <fawcett at uwindsor.ca>
> wrote:
> 
>> On Mon, 18 Apr 2011 10:03:10 -0400, Steven Schveighoffer wrote:
>>
>>> On Mon, 18 Apr 2011 09:44:38 -0400, lenochware <lenochware at gmail.com>
>>> wrote:
>>>
>>>> == Quote from Steven Schveighoffer (schveiguy at yahoo.com)'s article
>>>>> On Mon, 18 Apr 2011 04:31:26 -0400, %u <lenochware at gmail.com> wrote:
>>>>> > Is it necessary free memory allocated for member of structure,
>>>>> > like in C? I
>>>>> > suppose not (we have gc). Example:
>>>>> >
>>>>> > struct BITMAP {
>>>>> > (...)
>>>>> > ubyte[] pixels;
>>>>> > }
>>>>> >
>>>>> > BITMAP* bitmap = new BITMAP;
>>>>> > bitmap.pixels = new ubyte[100*100];
>>>>> > (...)
>>>>> >
>>>>> > // delete bitmap.pixels; //not necessary?
>>>>> >
>>>>> > delete bitmap;
>>>>> It is not necessary, because pixels will be collected by the GC
>>>>> sometime in the future.  It will *not* free pixel's data by calling
>>>>> delete on the BITMAP pointer.
>>>>> Just a note, you may be tempted to use a destructor do effect the
>>>>> above (as is done in C++ commonly), but this is a very big mistake.
>>>>
>>>> So what is "correct" way to manage structures like BITMAP? Don't
>>>> bother with
>>>> freeing memory at all?
>>>
>>> In most cases yes.  Freeing memory manually is dangerous (the compiler
>>> cannot verify that there are no other references to that memory), and
>>> should only be used when optimizing performance, or to workaround
>>> runtime deficiencies like false pointers.
>>>
>>> In essence, you should avoid freeing memory unless you know what you
>>> are doing.  It's very possible you do know that it's OK.
>>
>> Would "bitmap.pixels = null;" be a safe compromise? If you know you're
>> not going to use "pixels" any more, this would mark it as reclaimable,
>> but any other references to the array will keep it alive.
> 
> The recommended alternative to destruction is to use clear, since it
> runs the appropriate finalizers, plus sets it to null.

Thanks for that. The documentation for std.array.clear() is rather terse 
("clears the managed array"), so your explanation is very helpful.

Best,
Graham

> 
> If you delete bitmap, the runtime sets it to null already.  So nothing
> would be referencing pixels.
> 
> But yes, setting to null cannot ever hurt.  It does not accomplish any
> freeing of memory immediately though.
> 
> -Steve



More information about the Digitalmars-d mailing list