How to make sure a function is only called once

前端 未结 5 1755
半阙折子戏
半阙折子戏 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:22

    You could use this:

    void caller()
    {
        static class Once { public: Once(){callee();}} Once_;
    }
    
    0 讨论(0)
  • 2021-01-31 18:22

    Inspired by some people, I think just use a macro to wrap comma expression would also make the intention clear:

    #define CALL_ONCE(func) do {static bool dummy = (func, true);} while(0)
    
    0 讨论(0)
  • 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.)

    0 讨论(0)
  • 2021-01-31 18:31

    Thread-safe:

        static boost::once_flag flag = BOOST_ONCE_INIT;
        boost::call_once([]{callee();}, flag);  
    
    0 讨论(0)
  • 2021-01-31 18:34

    You could hide the function through a function pointer.

    static void real_function()
    {
      //do stuff
    
      function = noop_function;
    }
    
    
    static void noop_function()
    {
    
    }
    
    int (*function)(void) = real_function;
    

    Callers just call the function which will do the work the first time, and do nothing on any subsequent calls.

    0 讨论(0)
提交回复
热议问题