1. 19
  1.  

  2. 14

    I wouldn’t call defer a “very elegant solution” when RAII exists :)

    1. 7

      The problem for RAII is that it needs to be in a class destructor. Defer can just happen by writing a line of free code.

      1. 7

        Except RAII can handle the case where ownership is transferred to some other function or variable. Also, it scales well to nested resources, whereas figuring out which of any structs in a given C library require a (special) cleanup call is depends entirely on careful reading of the relevant documentation. If RAII was just about closing file handles at the end of the function, few people would care.

        1. 2

          Except RAII can handle the case where ownership is transferred to some other function or variable.

          Does that matter for languages that have GC?

          1. 7

            RAII is not exclusive to memory management. The Resource in RAII can be aquired memory, but it can also equally be an open file-descriptor, socket or any other resource for that matter, that GC won’t collect.

          2. 1

            I think the ideal solution would be to be able to use class destructors for some things, but also be able to add a block to the “destruction” of a specific instance.

        2. 3

          Doesn’t RAII sort of hide the cleanup from your actual code? I imagine that can work only if one can trust that every library you ever use behaves well in this manner. Then again, I guess an explicitly called cleanup routine may be of poor quality as well.

          1. 8

            That’s the point. Cleanup is automatic, deterministic, invisible. You can’t forget it, while you definitely can forget a defer something.close().

            Every library in Rust does behave like this, and I guess pretty much every library in C++ (that you would actually want to use) does as well.

          2. 3

            Excellent point! Now it feels only slightly more elegant than goto :)

          3. 12

            Nested functions in Swift aren’t too modern. They were in ALGOL, Simula 67, and Pascal.

            1. 2

              Yeah, most of these techniques would work in any modern language. I assume the target audience is recidivist C coders.

              1. 1

                The goal was to demonstrate how modern code, as in code you’d write today in Swift, would solve the same problems without relying on goto or multiple inheritance. I don’t claim that Swift pioneered any of this or that any of it is novel.