Destructors and finalizers 00:00:00 Make a prediction You will choose deterministic cleanup for a resource and test the failure path that must release it. A program opens a file and then throws before reaching the close line at the bottom. Is it safe to wait for the garbage collector to free the file before the next operation? No. Reclamation time varies and a handle may be needed immediately. Scope-based cleanup or a finally block releases the file when control leaves the protected region. 00:00:29 The lamps must come back Cavers borrow lamps. A return hook on the exit catches a lamp whenever its wearer leaves, even in a sudden rush. A caretaker who eventually picks up abandoned lamps cannot promise when the next group will have one. A resource guard ties cleanup to a known crossing of the boundary. A finalizer is more like the occasional caretaker and is a poor owner of a deadline-sensitive release. A destructor is code that runs when an object's life ends, at a moment you can point at in the source. In C++ it is ~File, and it runs at the closing brace of the block that owns the object. It takes no parameters, and a class has exactly one. Memory is plenty and a collector finds it. Other resources are few, and nobody looks for them: a database may allow 100 connections, a process may open some thousand files, and a lock has one holder. 00:01:24 Return a file handle on every exit Open a report file and begin writing. An encoding error halfway through must still release the operating-system handle. In Python, a context manager closes it when the block exits. In C++, a suitably scoped owner releases it in its destructor during normal stack unwinding. A later write cannot rely on a garbage collector running at a predictable time. Test the error path as well as successful completion. Hold the file open, force a write error, and immediately ask another writer to open the same resource. A scope-based close runs even on the failed path. Waiting for eventual garbage collection can make this test pass sometimes while leaving handles exhausted under steady load. 00:02:09 Release a lock after an exception Acquire a lock around an update. The update raises an exception before the explicit unlock line. A scope guard or try-finally releases the lock on that path. A finalizer invoked at some unknown future time cannot reliably unblock the next waiting thread. Now force an exception one statement after taking a lock. A second worker should eventually enter the protected region. If release sits only at the bottom of the success path, that worker waits indefinitely. The guard must cover exactly the interval in which the update owns the lock. A process killed abruptly may not run ordinary cleanup code. Do not promise that a destructor completes a distributed transaction under every failure. For a file or lock owned within one scope, a context manager or resource guard makes ordinary return and exception paths share the same cleanup rule. A lock guard in C plus plus owns the duty to release a mutex when its scope ends. A unique pointer owns an object and destroys it when that ownership ends. Both tie cleanup to a predictable lifetime, so returning early or raising an exception still follows the release path. 00:03:26 Try an interview follow-up How do you find a connection leak in production? Record where each lease was taken, log the ones that are out too long, and graph the number in use. A line that climbs in steps and never falls is a leak. Then look at the recorded places, usually an early return or an error path. A function transfers its open file handle to a writer object. Which scope should close the handle now? The contract has to name the new owner. If the original scope closes after the handoff, the writer receives an unusable handle. If neither closes, the resource leaks. Test an early return on each side of the handoff. 00:04:12 What to take with you Tie each resource to a block: RAII in C++, with in Python, try-with-resources in Java, using in C sharp and TypeScript, defer in Go. It is released on every way out, in reverse order. Make close idempotent, with one owner, and do not let it hide the error that was already flying. Report its own error where somebody can read it.