How to delete dynamic array ?

Dicebot public at dicebot.lv
Mon Dec 30 01:07:51 PST 2013


Answer will make more sense if ar is assumed to be any 
heap-allocated object, not just dynamic array.

On Monday, 30 December 2013 at 06:52:20 UTC, Ilya Yaroshenko 
wrote:
> case 1:
>  delete ar;

Deprecated. Used to call destructor and GC.free after that

> case 2:
>  ar.destroy();

Current solution to free resources in deterministic way. Calls 
destructor and sets `ar` to init state so that it can be 
collected by GC at some unknown point later.

> case 3:
>  GC.free(ar.ptr);

Marks memory as freed in GC. Unsafe and discouraged because there 
can still be references pointing at it.

> case 4:
>  ar = null;// (assumed that ar is only one pointer to the same 
> array)

Simply cleans the reference to an object. If it was the only 
reference, it will be destroyed and freed upon next GC cycle.

> What is the difference?
>
> How to free memory to the system immediately?

GC.free

However, if you want deterministic deallocation it makes more 
sense to use C malloc or custom allocators as GC tends to run 
faster if it is aware of less memory.


More information about the Digitalmars-d-learn mailing list