Using static function variable vs class variable to store some state

ε祈祈猫儿з 提交于 2020-01-03 13:36:06

问题


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)


回答1:


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.



来源:https://stackoverflow.com/questions/38353035/using-static-function-variable-vs-class-variable-to-store-some-state

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