logoalt Hacker News

flohofwoelast Sunday at 4:45 PM4 repliesview on HN

Not possible, you'll need to pass the captured variables explicitly into the 'lambda' via some sort of context parameter.

And considering the memory management magic that would need to be implemented by the compiler for 'painless capture' that's probably a good thing (e.g. there would almost certainly be a hidden heap allocation required which is a big no-no in Zig).


Replies

pton_xdlast Sunday at 4:59 PM

As far as I know lambdas in C++ will not heap allocate. Basically equivalent to manually defining a struct, with all your captures, and then stack allocating it. However if you assign a lambda to a std::function, and it's large enough, then you may get a heap allocation.

Making all allocations explicit is one thing I do really like about Zig.

tsimionesculast Monday at 1:02 PM

If the lambda is a value type, you can just store whatever captures you want in the fields of this type, no need for heap allocations - they'll go on the stack just like anything else. You can even ask the user to explicitly specify which variables to capture, like in C++ lambdas, to be very explicit about the size of the lambda structure.

andrepdlast Sunday at 5:57 PM

Why would capturing require a heap allocation? Neither Rust nor C++ do this.

show 1 reply
nine_klast Sunday at 4:58 PM

...or escape analysis and lifetimes, but we already have Rust %)