How to make sure a function is only called once

前端 未结 5 1757
半阙折子戏
半阙折子戏 2021-01-31 17:56

Suppose I have a function named caller, which will call a function named callee:

void caller()
{
    callee();
}  

Now caller might be called m

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-31 18:25

    Your first variant with a boolean flag bFirst is nothing else that an explict manual implementatuion of what the compiler will do for you implictly in your other variants.

    In other words, in a typical implementation in all of the variants you pesented so far there will be an additional check for a boolean flag in the generated machine code. The perfromance of all these variants will be the same (if that's your concern). The extra code in the first variant might look less elegant, but that doesn't seem to be a big deal to me. (Wrap it.)

    Anyway, what you have as your first variant is basically how it is normally done (until you start dealing with such issues as multithreading etc.)

提交回复
热议问题