| ▲ | mort96 2 hours ago | |||||||||||||||||||
> Most of the languages that have finally clauses also have destructors. Hm, is that true? I know of finally from Java, JavaScript, C# and Python, and none of them have proper destructors. I mean some of them have object finalizers which can be used to clean up resources whenever the garbage collector comes around to collect the object, but those are not remotely similar to destructors which typically run deterministically at the end of a scope. Python's 'with' syntax comes to mind, but that's very different from C++ and Rust style destructors since you have to explicitly ask the language to clean up resources with special syntax. Which languages am I missing which have both try..finally and destructors? | ||||||||||||||||||||
| ▲ | brewmarche an hour ago | parent | next [-] | |||||||||||||||||||
In C# the closest analogue to a C++ destructor would probably be a `using` block. You’d have to remember to write `using` in front of it, but there are static analysers for this. It gets translated to a `try`–`finally` block under the hood, which calls `Dispose` in `finally`.
Or, to avoid nesting:
These also is `await using` in case the cleanup is async (`await foo.DisposeAsync()`)I think Java has something similar called try with resources. | ||||||||||||||||||||
| ▲ | jchw 2 hours ago | parent | prev | next [-] | |||||||||||||||||||
I don't view finalizers and destructors as different concepts. The notion only matters if you actually need cleanup behavior to be deterministic rather than just eventual, or you are dealing with something like thread locals. (Historically, C# even simply called them destructors.) | ||||||||||||||||||||
| ||||||||||||||||||||
| ▲ | dist-epoch 2 hours ago | parent | prev [-] | |||||||||||||||||||
Technically CPython has deterministic destructors, __del__ always gets called immediately when ref count goes to zero, but it's just an implementation detail, not a language spec thing. | ||||||||||||||||||||