开发者

Are there any problems with changing the target of a function pointer from within the function? (C++)

I have a program that defines changes the target function of a function pointer from within the function being called by said pointer, like so:

void increment(int&);
void superincrement(int&);

void (*fooncrement)(int&);

int main() {
    int j = 0;
    fooncrement = increment;
    while (true == true) {
        fooncrement(j);
    }
}

void incre开发者_C百科ment(int& i) {
    static int counter = 0;

    i++;

    if (counter > 7)
        fooncrement = superincrement;
    counter++;
}

void superincrement(int& i) {
    i += 23;
}

A quick run through MSVC's debugger shows that the program more or less works as expected. However, are there are any problems not immediately obvious here that might manifest if I tried something like this in a more complex environment?


This is well-defined.

In fact, this technique is often used to implement state machines.


No, there shouldn't be any problem. It's not like it clings to that pointer once you made the call.


This isn't thread-safe, but for single-threaded apps, no problems. If you don't know what threading is, then you're not using it, so you have no problem.

More advanced programs use multiple "threads", each of which is basically it's own program, but they work together. Imagine if you had int main(), but also int main1(), int main2(), int main3(), and they all ran at the same time. Your program could do four things at once! However, if one thread changes fooncrement, there will be a slight delay before the other threads see the updated value. In the meantime, they'd use the old value, which might cause problems.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜