Function Call Guard

c++, call, function, guard

Solution

You can do it with some different ugliness:

struct InitFoo
{
     InitFoo()
     {
         // one-time code goes here
     }
};

void Foo()
{
    static InitFoo i;
}

You're still using `static`, but now you don't need to do your own flag checking - `static` already puts in a flag and a check for it, so it only constructs `i` once.

Problem

Suppose I have a free function called `InitFoo`. I'd like to protect this function from being called multiple times by accident. Without much thought I wrote the following: ``` void InitFoo() { { static bool flag = false; if(flag) return; flag = true; } //Actual code goes here. } ``` This looks like a big wart, though. `InitFoo` does not need to preserve any other state information. Can someone suggest a way to accomplish the same goal without the ugliness? Macros don't count, of course.

Original source