When I should to call destroy?

Lodovico Giaretta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jul 29 06:41:48 PDT 2016


On Friday, 29 July 2016 at 13:18:00 UTC, Suliman wrote:
> Use the `destroy` function to finalize an object by calling its 
> destructor. The memory of the object is not immediately 
> deallocated, instead the GC will collect the memory of the 
> object at an undetermined point after finalization:
>
> class Foo { int x; this() { x = 1; } }
> Foo foo = new Foo;
> destroy(foo);
> assert(foo.x == int.init);  // object is still accessible
>
>
> But I can't understand if D have GC it should remove objects 
> when their life is finished. When I should to call `destroy`? 
> What would be if I will not call it?

Destroy will call the destructors, but memory will not actually 
be deallocated before the next GC cycle. It is used because the 
GC cycle does not guarantee to run the destructors, so using 
destroy the destructor is ran immediately (guaranteed). Then, on 
next GC iteration, the memory will be freed. Until then, 
referencing it will not cause segfault, but will cause undefined 
behaviour, as after a destructor the state of the object is 
undefined (I think).


More information about the Digitalmars-d-learn mailing list