5

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)

erip
  • 16,374
  • 11
  • 66
  • 121
isamert
  • 482
  • 4
  • 12

1 Answers1

5

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.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • but then it is mandatory to carry this object whenever it needed. – Humam Helfawi Jul 13 '16 at 13:29
  • @HumamHelfawi: What do you mean? If it is "needed" then of course it is "mandatory." – John Zwinck Jul 13 '16 at 13:30
  • So you are saying there isn't any in-line solutions for this. What about using static variable solution in one-instanced(I mean, if I know that class has only one instance for sure) classes. Are there any other pitfalls for this situation? – isamert Jul 13 '16 at 13:31
  • I mean if you need to call this function from some other function, you have to instance an object of the Foo class. and if you want to use it from another function, you can not just instance a new one you have to still passing it from place to another each time. – Humam Helfawi Jul 13 '16 at 13:32
  • 4
    @isamert: The pitfall is that there is no such thing as a class which will definitely only have one instance. Design requirements change. Singletons are not good. – John Zwinck Jul 13 '16 at 13:58