[ACCEPTED]-How to make sure a function is only called once-c++

Accepted answer
Score: 19

You could use this:

void caller()
    static class Once { public: Once(){callee();}} Once_;


Score: 13


    static boost::once_flag flag = BOOST_ONCE_INIT;
    boost::call_once([]{callee();}, flag);  


Score: 7

You could hide the function through a function 3 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 2 do the work the first time, and do nothing 1 on any subsequent calls.

Score: 2

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

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

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

Score: 0

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

#define CALL_ONCE(func) do {static bool dummy = (func, true);} while(0)

More Related questions