使用静态函数变量vs类变量来存储一些状态 [英] Using static function variable vs class variable to store some state

查看:87
本文介绍了使用静态函数变量vs类变量来存储一些状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的功能:

  void processElement(){
doSomething(someArray [lastProcessedElement + 1]);事情是,每次这个函数调用时,我需要到存储库中。最后一个元素,我叫doSomething。所以在这里我有两个选择:




  • 我可以创建一个私有类变量名为lastProcessedElement,叫做。这种方法似乎最常见。所以代码可以这样:

      class Foo {
    int lastProcessedElement = 0;

    public:
    void processElement(){
    doSomething(someArray [++ lastProcessedElement]);
    }
    }


  • 作为第二个选项,函数中的静态变量并且每次都增加:

      //类在这里不重要,因此函数是:
    void processElement(){
    static int lastProcessedElement = 0;
    doSomething(someArray [++ lastProcessedElement]);
    }




有点复杂,我不想要。



我知道第二个解决方案只有在该类只有一个实例时才有效。



那么使用静态变量方法是一个很好的解决方案?并且有多任务在线解决方案多实例类? (可以有一个解决方案,这个特定的数组元素索引的东西,但我只是这样,我说的是存储一些值的函数的下一次调用)

解决方案

您已经知道为什么函数范围的静态是一个坏主意:



这是一个不好的设计限制。



只需将状态保持为常规类成员变量。


Lets say I have function like this:

void processElement() {
    doSomething(someArray[lastProcessedElement + 1]);
}

The thing is, every time this function called, I need to the store the last element that I called doSomething on. So in here I have two choices:

  • I can create a private class variable named lastProcessedElement and increment it's value every time that function is called. This approach seems most common. So the code can be something like this:

    class Foo {
        int lastProcessedElement = 0;     
    
        public:  
        void processElement() {
            doSomething(someArray[++lastProcessedElement]);
        }
    }
    

  • As second option, I can create a static variable in function and increment it every time:

    // Class is not important here, so the function is:
    void processElement() {
        static int lastProcessedElement = 0;
        doSomething(someArray[++lastProcessedElement]);
    }
    

The first solution adds a little bit complexity which I don't want. I like to keep things in-place.

I know the second solution only works if that class have only one instance.

So using static variable method is a good solution? And is there any in-line solution to multi-instance class? (There can be a solution to this particular array element index thing, but I just made that up, I'm talking about storing some value for the next call of the function)

解决方案

You already figured out why the function-scoped static is a bad idea:

only works if that class have only one instance

That's a bad design limitation.

Just keep the state as a regular class member variable.

这篇关于使用静态函数变量vs类变量来存储一些状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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