Darzen Darzen - 3 months ago 13
C++ Question

How to execute a piece of code only once?

I have an application which has several functions in it. Each function can be called many times based on user input. However I need to execute a small segment of the code within a function only once, initially when the application is launched. When this same function is called again at a later point of time, this particular piece of code must not be executed. The code is in VC++. Please tell me the most efficient way of handling this.


Use global static objects with constructors (which are called before main)? Or just inside a routine

static bool initialized;
if (!initialized) {
   initialized = true;
   // do the initialization part

There are very few cases when this is not fast enough!


You may also be interested in pthread_once or constructor function __attribute__ of GCC

But these might not be available on your system; they are available on Linux!