logoalt Hacker News

torginus • today at 10:36 AM • 2 replies • view on HN

Each to their own I guess, by personally I really don't like closures (at least ones that as per their namesake, close over objects with nontrivial lifetimes).

I think it was the right call by the C++ people to explicitly list what objects are captured and how, even if the syntax's not the best.

RAII is a fact of life unfortunately, not just in C++ or Rust, but if you talk over some high level protocol over the internet you go TCP socket->HTTP connection->your stream protocol; and have to do the exact reverse.

Closures break RAII hard.

Incidentally, you don't even need closures for nice looking UI code. Immediate mode GUIs like Dear Imgui or Clay allow for super-simple looking code in basic C


Replies

amelius • today at 11:59 AM

> Immediate mode GUIs like Dear Imgui or Clay allow for super-simple looking code in basic C

Layout computation is always awkward in immediate guis. You have to do an extra pass or throw away a frame.

Xirdus • today at 11:26 AM

> I think it was the right call by the C++ people to explicitly list what objects are captured and how

Having recently worked a lot with Rust, which does this implicitly - I find the explicit notation entirely unnecessary. There's only one choice - are captures moved into closure or passed by reference? - and everything else is inferred. It does lead to some verbose cloning when there are many refcounting pointers at play, but other than that it works flawlessly; I've never been in a situation I couldn't do something I wanted to.

I'm confused by the point about RAII. Why are you saying that closures break it? Personally, I found that closures complement RAII very well - the closure owns its resources, and when it goes out of scope they're all cleaned up automatically. Or do you mean situations where resources outlive the closures? This is no different than any other object that needs a reference to something that lives longer.