Initializing part of function only once

2019-02-26 08:45发布

问题:

I have a function with a small bit which I want to initialize once e.g.

void SomeFunc()
{
static bool DoInit = true;
if (DoInit)
   {
   CallSomeInitCode();
   DoInit = false;
   }
// The rest of the function code
}

If this function is called many times it leaves one unnecessary if (DoInit) which can't be optimized. So why don't I do initialization elsewhere like constructor? Because, logically this initialization code best fits inside this function and it is easier to maintain that way, despite the fact it will do unnecessary check every time.

Is there a better way to do this without resorting to using the construct in above example?

回答1:

You can do it by building a class that calls initialization code in its constructor, like this:

class InitSomething {
public:
    InitSomething() {
        CallSomeInitCode();
    }
};

Now you can do this:

void SomeFunc() {
    static InitSomething myInitSomething;
    ...
}

The object will be constructed once, executing the CallSomeInitCode exactly one time.