top | item 45854089

(no title)

krosaen | 3 months ago

I like the idea of the `defer `keyword - you can have automatic cleanup at the end of the scope but you have to make it obvious you are doing so, no hidden execution of anything (unlike c++ destructors).

discuss

order

jibal|3 months ago

Adopted from go, first appeared in D, invented by one of its major developers, Andrei Alexandrescu.

jibal|3 months ago

P.S. In D it's `scope(exit)` = defer, `scope(failure)` = Zig's errdefer, and `scope(success)` -- which no one else has and which I have made good use of. e.g., I have a mixin that traces entry and exit from a function, the latter with scope(success). If I use scope(exit) instead then when an exception is thrown all the leave messages are printed and then the stack trace, rather than seeing the stack trace at the point of failure (this baffled me when it first happened).

fuzztester|3 months ago

I vaguely remember reading somewhere recently that Andrei left the D community / foundation. Do you know if that is true?

tcfhgj|3 months ago

But you can forget it, unlike C++ destructors

coolThingsFirst|3 months ago

C++ doesn't have hidden execution, you just don't know the language. Once you exit scope destructor is invoked.

lenkite|3 months ago

I would like a language to support both defer and C++ style destructors / Rust Drop. There are good use-cases for having both. For things like a mutex or straight-forward resource cleanup - having a bunch of brain-dead defer statements adds little value and only bloats unnecessary line count. Let the resource type handle its own release/cleanup at scope close. Code is made sweet, succinct and safe.

rustacean|3 months ago

In Rust, there’s a drop guard pattern to do this, which leverages the lazy execution of closure, checkout the scopeguard crate. C++ should be easy to do that too I think