7 ms·
Destructors are vastly superior to the finally keyword because they only require us to remember a single time to release resources (in the destructor) as oppose
by winternewt 9mo ago
Destructors are vastly superior to the finally keyword because they only require us to remember a single time to release resources (in the destructor) as opposed to every finally clause. For example, a file always closes itself when it goes out of scope instead of having to be explicitly closed by the person who opened the file. Syntax is also less cluttered with less indentation, especially when multiple objects are created that require nested try... finally blocks. Not to mention how branching and conditional initialization complicates things. You can often pair up constructors with destructors in the code so that it becomes very obvious when resource acquisition and release do not match up.
- jchw 9mo agoDestructors and finally clauses serve different purposes IMO. Most of the languages that have finally clauses also have destructors. > Syntax is also less cluttered with less indentation, especially when multiple objects are created that require nested try... finally blocks. I think that's more of a point against try...catch/maybe exceptions as a whole, rather than the finally block. (Though I do agree with that. I dislike that aspect of exceptions, and generally prefer something closer to std::expected or Rust Result.)
- mort96 9mo 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?
- dist-epoch 9mo agoTechnically 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.
- jchw 9mo agoI 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.)
- mort96 9mo agoThere's a huge difference in programming model. You can rely on C++ or Rust destructors to free GPU memory, close sockets, free memory owned through an opaque pointer obtained through FFI, implement reference counting, etc. I've had the displeasure of fixing a Go code base where finalizers were actively used to free opaque C memory and GPU memory. The Go garbage collector obviously didn't consider it high priority to free these 8-byte objects which just wrap a pointer, because it didn't know that the objects were keeping tens of megabytes of C or GPU memory alive. I had to touch so much code to explicitly call Destroy methods in defer blocks to avoid running out of memory.
- cogman10 9mo agoFor GCed languages, I think finalizers are a mistake. They only serve to make it harder to reason about the code while masking problems. They also have negative impacts on GC performance. Java is actively removing it's finalizers.
- adrianN 9mo agoSometimes „eventually“ is „At the end of the process“. For many resources this is not acceptable.
- rramadass 9mo ago
- sigwinch28 9mo agoA writable file closing itself when it goes out of scope is usually not great, since errors can occur when closing the file, especially when using networked file systems. https://github.com/isocpp/CppCoreGuidelines/issues/2203 https://github.com/isocpp/CppCoreGuidelines/issues/2203
- leni536 9mo agoAny fallible cleanup function is awkward, regardless of error handling mechanism.
- layer8 9mo agoJava solved it by having exceptions be able to attach secondary exceptions, in particular those occurring during stack unwinding (via try-with-resources). The result is an exception tree that reflects the failures that occurred in the call tree following the first exception.
- NBJack 9mo agoI often miss this feature in other languages. It has saved me more times than I can count.
- mort96 9mo agoYou need to close it and check for errors as part of the happy path. But it's great that in the error path (be that using an early return or throwing an exception), you can just forget about the file and you will never leak a file descriptor. You may need to unlink the file in the error path, but that's best handled in the destructor of a class which encapsulates the whole "write to a temp file, rename into place, unlink on error" flow.
- dist-epoch 9mo agoPython has that too, it's called a context manager, basically the same thing as C++ RAII. You can argue that RAII is more elegant, because it doesn't add one mandatory indentation level.
- logicchains 9mo agoIt's not the same thing at all because you have to remember to use the context manager, while in C++ the user doesn't need to write any extra code to use the destructor, it just happens automatically.
- kibwen 9mo agoTo be fair, that's just an artifact Python's chosen design. A different language could make it so that acquiring the object whose context is being managed could require one to use the context manager. For example, in Python terms, imagine if `with open("foo") as f:` was the only way to call `open`, and gave an error if you just called it on its own.
- mort96 9mo agoHow do you return a file in the happy path when using a context manager? If you can't, it's not remotely "basically the same as C++ RAII".
- yoshuaw 9mo agoI couldn't agree more. And in the rare cases where destructors do need to be created inline, it's not hard to combine destructors with closures into library types. To point at one example: we recently added `std::mem::DropGuard` [1] to Rust nightly. This makes it easy to quickly create (and dismiss) destructors inline, without the need for any extra keywords or language support. [1]: https://doc.rust-lang.org/nightly/std/mem/struct.DropGuard.html https://doc.rust-lang.org/nightly/std/mem/struct.DropGuard.h...
- raverbashing 9mo agoBut they're addressing different problems Sure destructors are great but you still want a "finally" for stuff you can't do in a destructor
- mandarax8 9mo agoThe entire point of the article is that you cannot throw from a destructor. Now how do you signal that closing/writing the file in the destructor failed?
- DonHopkins 9mo agoThat tastes like leftover casserole instead of pizza.
- EPWN3D 9mo agoJust panic. What's the caller realistically going to do with that information?
- deleted 9mo ago[deleted]
- winternewt 9mo agoYou are allowed to throw from a destructor as long as there's not already an active exception unwinding the stack. In my experience this is a total non-issue for any real-world scenario. Propagating errors from the happy path matters more than situations where you're already dealing with a live exception. For example: you can't write to a file because of an I/O error, and when throwing that exception you find that you can't close the file either. What are you going to do about that other than possibly log the issue in the destructor? Wait and try again until it can be closed? If you really must force Java semantics into it with chains of exception causes (as if anybody handled those gracefully, ever) then you can. Get the current exception and store a reference to the new one inside the first one. But I would much rather use exceptions as little as possible.
- locknitpicker 9mo ago> The entire point of the article is that you cannot throw from a destructor. You need to read the article again because your assertion is patently false. You can throw and handle exceptions in destructors. What you cannot do is not catch those exceptions, because as per the standard uncaught exceptions will lead the application to be immediately terminated.
- WalterBright 9mo agoThe scope guard statement is even better! https://dlang.org/articles/exception-safe.html https://dlang.org/articles/exception-safe.html https://dlang.org/spec/statement.html#ScopeGuardStatement https://dlang.org/spec/statement.html#ScopeGuardStatement Yes, D also has destructors.
- Defletter 9mo agoScope guards are neat, particularly since D has had them since 2006! (https://forum.dlang.org/thread/dtr2fg$2vqr$4@digitaldaemon.com https://forum.dlang.org/thread/dtr2fg$2vqr$4@digitaldaemon.c...) But they are syntactically confusing since they look like a function invocations with some kind of aliased magic-value passed in.
- indiosmo 9mo agoI use this library a lot for scope guards in C++ https://github.com/Neargye/scope_guard https://github.com/Neargye/scope_guard, especially for rolling back state on errors, e.g. In a function that inserts into 4 separate maps, and might fail between each insert, I'll add a scope exit after each insert with the corresponding erase. Before returning on success, I'll dismiss all the scopes. I suppose the tradeoff vs RAII in the mutex example is that with the guard you still need to actually call it every time you lock a mutex, so you can still forget it and end up with the unreleased mutex, whereas with RAII that is not possible.
- WalterBright 9mo agoThe tradeoff with RAII is once you have 3 things that must all succeed or all fail, that is very clumsy to do with RAII, but easy with scope guard.