仅部分函数初始化一次 [英] Initializing part of function only once

查看:117
本文介绍了仅部分函数初始化一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小的功能,我想初始化一次

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.

这篇关于仅部分函数初始化一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆