3 ms·
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 exec
by krosaen 11mo 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).
- jibal 11mo agoAdopted from go, first appeared in D, invented by one of its major developers, Andrei Alexandrescu.
- jibal 11mo agoP.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 11mo agoI vaguely remember reading somewhere recently that Andrei left the D community / foundation. Do you know if that is true?
- jibal 11mo agoHe's moved on: https://research.nvidia.com/person/andrei-alexandrescu https://research.nvidia.com/person/andrei-alexandrescu
- tcfhgj 11mo agoBut you can forget it, unlike C++ destructors
- lenkite 11mo agoI 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 11mo agoIn 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
- 1718627440 11mo agoGNU C++?
- 1718627440 11mo agoThe GNU C and C++ dialect also has attribute cleanup. https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html#index-cleanup-variable-attribute https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attribute...
- coolThingsFirst 11mo agoC++ doesn't have hidden execution, you just don't know the language. Once you exit scope destructor is invoked.