Initializing part of function only once

本秂侑毒 提交于 2019-12-02 02:18:35

问题


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.



来源:https://stackoverflow.com/questions/16511815/initializing-part-of-function-only-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!