by codeflo · 4y ago · 0 comments
Here's one important difference: Destructors work in standard data structures. If for whatever reason you want to build a map<string, list<fstream>>, and the map goes out of scope, all files are correctly closed. (Rust's drop semantics work the same way.) That's a lot more work in Java or C#.
Yes, that means they hang around a lot longer, and that's sometimes problematic, but that's the GC way.
For resources like memory, where it’s merely a question of performance, I would agree. But some resources have correctness implications. Files, for example, you often want to close deterministically. It’s simply a terrible experience if a user can’t save because a file handle from a previous operation still lingers in a GC queue somewhere.
That’s also the reason why language features like try-with-resources were added in the first place.