Object destruction versus finalization

Florian santa at nortpole.org
Tue Nov 12 12:15:00 PST 2013


I played around a little and figured out, that destructors in D 
work quite similarily to destructors in C++. They are invoked, 
after the members of the instance being destructed have been 
destroyed themselfes (or at least have been brought into an 
invalid state). Therefore, these members cannot be accessed 
savely from inside the destructor.

In contrast, Java and C# offer a concept called finalizer. When 
the finalizer is called, all members of the instance itself are 
still valid and are guaranteed to be freely accessible. This 
behaviour can be useful for some cleanup operations.

Managed C++ offers both, C#-like finalizers and conventional C++ 
destructors, where the destructor is called ~className and the 
finalizer is called !className. Is their a best practice to 
mimikry this behaviour, i.e. to call a certain block of code when 
an object is being garbage collected, but before its contents 
render invalid?

Any hints would be greatly appreciated.


More information about the Digitalmars-d-learn mailing list