I have this code:
void foo(void (*bar)()) {
bar();
}
int main() {
foo([] {
int x = 2;
});
}
However, I\'m worried that
In addition to Nicol's perfectly correct general answer, I would add some views on your particular fears:
However, I'm worried that this will suffer the same fate as ..., which takes the address of a local variable.
Of course it does, but this is absolutely no problem when you just call it inside foo
(in the same way your struct example is perfectly working), since the surrounding function (main
in this case) that defined the local variable/lambda will outlive the called function (foo
) anyway. It could only ever be a problem if you would safe that local variable or lambda pointer for later use. So
Is the first example completely safe?
Yes, it is, as is the second example, too.