4 ms·
Destructors in C++ aren't just for making sure you leak memory. They are used for many lifetime controlled things such as: 1. general resource cleanup (file ha
by msclrhd 6y ago
Destructors in C++ aren't just for making sure you leak memory. They are used for many lifetime controlled things such as:
1. general resource cleanup (file handle, database connection, etc.) using RAII (Resource Aquisition Is Initialization);
2. tracing function entry/exit.
- mcguire 6y agoApparently, that doesn't work in Rust: https://news.ycombinator.com/item?id=23363647 https://news.ycombinator.com/item?id=23363647
- the8472 6y agoIt does work in rust. you just cannot rely on Drop for memory-safety. If you mem::forget a struct that holds onto some other resource then all that means is that you're committing that resource to the lifetime of the process. We usually call that a leak but it can be intentional.
- the_why_of_y 6y agoBy that argument, it doesn't work in C++ either because std::unique_ptr::release() exists.
- pdpi 6y agoIn the JVM the equivalent to RAII is implemented with try-with-resource/Autocloseable instead.
- cesarb 6y agoIn my experience, try-with-resources is inferior to RAII, since it's very easy to forget (that is, it's very easy to do "Foo x = bar();" instead of "try (Foo x = bar()) { ... }"), leading to resource leaks. More than once I have added a finalizer to an AutoCloseable class just to warn loudly if close() hasn't been called; unfortunately, there's no way that I know of to suppress the finalizer once close() is called, so the GC still has to do all the work to call the finalizer even when the class was used correctly.