Comment by fooker

6 days ago

How is defer not magic sauce?

Whether you consider it magic is up to you, but, unlike a destructor in RAII, there is nothing automatic going on. If you don't explicitly invoke a destructor, you won't get a destructor.

The fact that you can explicitly invoke the destructor to happen later is simply syntactic sugar, just like if/else/while, or any other control construct more powerful than a conditional jump instruction.

  • And more importantly, you can choose what destructor to call. This is perhaps what's most underrated about defer, because defer can select among many different destructors possible, at multiple different levels (group free with arenas, individual free, etc).

    • Or even whether you need a destructor, or something simpler, like nulling out a pointer or two to break a reference loop.

      defer is a perfectly general structured flow concept; it only cares about when you do something, and is completely orthogonal to what you need to accomplish.

      1 reply →

  • > If you don't explicitly invoke a destructor, you won't get a destructor.

    When you explicitly invoke a "destructor", you do it on many code paths (and miss one or two)

    >The fact that you can explicitly invoke the destructor to happen later

    You don't specify where the `defer`-red "destructor" will be invoked.

    • > When you explicitly invoke a "destructor", you do it on many code paths (and miss one or two)

      Unless, of course, you do it inside a defer block.

      > You don't specify where the `defer`-red "destructor" will be invoked.

      Yes, actually, you do. It is patently obvious, by code inspection, where the destructor, or anything else specified in a deferred block, will be invoked. defer is a perfectly cromulent part of structured control flow, allowing for easy reasoning about when things occur without having to calculate an insane number of permutations of conditional branch instructions.