Hacker News new | ask | show | jobs
by codeflo 1482 days ago
BTW, a lot of people in this thread compare destructors to Java's try-with-resource (similarly, C#'s using), or Go's defer.

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#.

1 comments

Won't Java or C# run the destructor eventually when they GC the equivalent of fstream?

Yes, that means they hang around a lot longer, and that's sometimes problematic, but that's the GC way.

To be technically correct, it’s called a finalizer in that case to distinguish it from deterministic destructors.

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.