Question

I have a callback implementation in which an unknown third party calls a function pointer in my code.

However, an issue in a lot languages is triggering code after a function returns. For instance, when a callback is called and I have to delete the calling object (and, in this case, re-initialize it), returning from the callback would cause an exception.

Assuming I cannot hook and that I do not own/cannot modify the code calling the callback, what is the best way to execute code after a function returns?

The only real way I can think of doing this is to set up some sort of state machine and have a worker thread check the state. However, the issue I foresee with this is that of a race condition, where a callback is called between the time the reset callback returns and the point the calling object is reset.

Is there any sort of functionality I'm not aware of, or would this be the most efficient way of achieving such a result?

Was it helpful?

Solution

It requires c++11 or newer though. But this is how i would do it. You can rewrite it to use function pointers instead so that it works on older c++ versions

#include <functional>
#include <iostream>

#define CONCACT_IMPL(x , y) x##y
#define CONCAT(x, y) CONCACT_IMPL(x, y)
#define deffered(x) auto CONCAT(__deffered, __COUNTER__)  = Defer(x);

struct Defer {
    Defer(std::function<void(void)> pFunc) : func(pFunc) {};
    std::function<void(void)> func;
    virtual ~Defer(){
        func();
    }
};

int main() {

    deffered([] () {
        std::cout << "deffered" << std::endl;
    });

    std::cout << "now" << std::endl;
}

outputs -->

now
deffered
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top