仅部分函数初始化一次
我有一个小的功能,我想初始化一次
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(DoInit)
,这是不能优化的。那么为什么我不在其他地方做初始化构造函数呢?因为,在逻辑上,这个初始化代码最适合这个函数,并且更容易维护,尽管事实上它会每次都做不必要的检查。
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?
你可以通过构建一个类调用初始化其构造函数中的代码,如下所示:
You can do it by building a class that calls initialization code in its constructor, like this:
class InitSomething {
public:
InitSomething() {
CallSomeInitCode();
}
};
现在可以这样做:
void SomeFunc() {
static InitSomething myInitSomething;
...
}
对象将被构造一次,执行 CallSomeInitCode
正好一次。
The object will be constructed once, executing the CallSomeInitCode
exactly one time.