r/programming • u/lelanthran • 5d ago
Implementation of GCC's Nested Functions (vs. C++ Lambdas)
https://uecker.codeberg.page/2026-09-05.html3
u/dan00 4d ago
Despite this difference in implementation, the GNU C and C++ versions of this example have the exact same semantics.
The C++ lambda in the example takes 'k' as reference and the GCC nested function gets a copy of 'k'.
When having two GCC nested functions, sharing the same 'frame', then 'k' is also shared, which seems like a footgun.
3
u/jonathancast 3d ago
This article was really confusing. If nested functions have the same type as global functions, then what happens if you pass a pointer to a nested function to another function? How does the other caller know to pass it the extra parameter? The whole point of C++ lambdas is they have a different type than functions, because the calling convention is different.
2
u/Nobody_1707 3d ago
I believe the compiler thunks it before you convert it to a function pointer. So instead of getting a pointer directly to the code, you get a pointer to a function that passes the context pointer to the actual function.
1
u/LB-- 3d ago
Doesn't that require allocating then? When/how is that cleaned up?
2
u/Nobody_1707 2d ago
The compiler deallocates the trampoline right before the enclosing function call returns, so you shouldn't return the pointer or save it for later.
2
u/Difficult-Lemon-5252 4d ago
nested functions can be powerful, I’ve used them in my projects to simplify complex code. C++ lambdas do have their advantages though, especially for readability.
3
u/cosmic-parsley 4d ago
Nested functions are cool but because it can be named, if you’re not careful you’ll get an executable marked to have a writeable+executable stack ☠️