jeudi 22 février 2018

Lifetime of lambda without capture [duplicate]

This question already has an answer here:

void set_callback(void (*fptr)());

void f() {
    auto callback = []() { std::cout << "callback" << std::endl; };
    set_callback(static_cast<void()>(callback));
}

set_callback is a library function that takes a function pointer void(*)() as argument. It will set a global state such that the function pointer is called after f has exited (possibly on another thread).

But callback is defined as a capture-less lambda in the scope of f, and converted to a function pointer when passed to set_callback. So its lifetime ends when f exits.

It the program still correct in this case? (Because the lifetime of the callback function itself is global).

If not, is it correct if callback is instead defined as static inside the function?

Aucun commentaire:

Enregistrer un commentaire