I'm using this little macro a lot:
#define RUN_ONCE(runcode) \
{ \
static bool code_ran = 0; \
if(!code_ran){ \
code_ran = 1; \
runcode; \
} \
}
I find it useful when I want to initialize stuff just once when I don't really care about performance (for example, if it's inside a render loop, it takes just 60 if's per sec). In a random generator, I can do RUN_ONCE(init_random())
, so I don't need to separately initialize it, which prevents me from crashing when I call the function without initializing it first.
I'd like to know if any of you use a similar system, and if there's better way of doing this. Or if I should stop using this method immediately...
magic statics
guarantees that a static value in function scope will be initialised exactly once even in the presence of multiple threads.static int result_of_run_once = runcode()
will do it right if yourruncode()
has a return value. Otherwise usestd::call_once
also since C++11. \$\endgroup\$