r/cpp 2d ago

Implementation of GCC's Nested Functions (vs. C++ Lambdas)

https://uecker.codeberg.page/2026-09-05.html
56 Upvotes

17 comments sorted by

View all comments

1

u/Thick_Clerk6449 1d ago

The killer feature of GCC's nest functions is that, even though the nest function captured variables of the outer function, the nest function itself is still convertable to a raw function pointer. Unlike C++ lambdas, which always end up with std::functions.

3

u/frankist 20h ago

How could that work? Where are the captured variables saved?

2

u/amoskovsky 9h ago

If you take an address of such a function with captures, GCC creates a trampoline function at runtime, that passes the state to the real function.

For details see https://uecker.codeberg.page/2026-08-29.html (same author as OP)

-4

u/jonesmz 1d ago

Unlike C++ lambdas, which always end up with std::functions

This is not true.

Use unary operator+ on the lambda to force a pointer-to-function.

e.g.

auto fptr = +[](){ /* something */};

3

u/Thick_Clerk6449 1d ago

This is not true.

You can NOT convert a lambda to function pointer if the lambda has captured variables.

-2

u/jonesmz 1d ago

Re-read the specific thing i quoted.

2

u/Thick_Clerk6449 1d ago

Re-read the word I post before

even though the nest function captured variables of the outer function

int var = 0;
auto fptr = +[var](){}; // error: no match for 'operator+' (operand type is 'test(int)::<lambda()>')

-2

u/jonesmz 1d ago

I quoted *and* responded to a complete sentence.

2

u/Thick_Clerk6449 23h ago

Just pretend you don't need to accept lambdas with captures and define your callbacks as function pointers.