What is a finalizer or destructor conceptually, and why are finalizers considered unreliable for resource cleanup?
Last updated
A finalizer/destructor is a method the runtime may call just before an object is reclaimed, letting it release non-memory resources like file handles or sockets (e.g. C++
~Class(), Python__del__). C++ stack destructors run predictably at scope exit (RAII).In garbage-collected languages the GC decides if and when finalizers run. Timing isn't guaranteed, they may never run (e.g. at process exit), ordering is undefined, and they slow collection.
Use deterministic disposal instead: C#
IDisposablewithusing, Java try-with-resources, Pythonwith. Keep finalizers only as a leak safety net.