Destructors and finalizers
medium 45 minSome things must be given back: files, connections, locks.
Watch lesson4:37
Where it shows up
The same pattern appears across everyday software.
std::lock_guard
cppreference describes it as an RAII-style wrapper that owns a mutex for the duration of a scoped block. No path can leave the block with the lock held.
std::unique_ptr
Owns an object and disposes of it when the pointer goes out of scope, with a deleter that you can choose, for example for a C library's handle.
Java try-with-resources
The tutorial notes that resources are closed in the opposite order of their creation, and that an exception from close is suppressed if the block already threw.
Python TemporaryDirectory
Used with `with`, the folder is removed at the end of the block. Destroying the object removes it as well, which is the net.
SQLAlchemy Session
The documentation uses the session as a context manager, so that it is closed at the end of the block.
HikariCP
`leakDetectionThreshold` logs a message if a connection has been out of the pool for longer than the given time. It is off by default.
Netty
Buffers are counted by hand because the JVM does not see them. About 1% of allocations are sampled, and a leak is printed with where it was used.
.NET SafeHandle
Microsoft's guide on Dispose wraps native handles in SafeHandle and asks that Dispose can be called many times without an error.
Rust Drop
A value's destructor runs when it goes out of scope. The compiler tracks ownership, so a moved value is not dropped twice.