logoalt Hacker News

winternewttoday at 12:03 PM6 repliesview on HN

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.


Replies

yoshuawtoday at 12:37 PM

I 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.h...

sigwinch28today at 12:17 PM

A 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

show 2 replies
mandarax8today at 1:23 PM

The 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?

show 4 replies
jchwtoday at 12:13 PM

Destructors 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.)

show 1 reply
raverbashingtoday at 1:19 PM

But they're addressing different problems

Sure destructors are great but you still want a "finally" for stuff you can't do in a destructor

dist-epochtoday at 12:24 PM

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

show 2 replies