Is it safe to cast a lambda function to a function pointer?

后端 未结 3 1251
北海茫月
北海茫月 2020-12-16 15:33

I have this code:

void foo(void (*bar)()) {
    bar();
}

int main() {
    foo([] {
        int x = 2;
    });
}

However, I\'m worried that

3条回答
  •  囚心锁ツ
    2020-12-16 16:06

    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.

提交回复
热议问题