isamert
isamert

Reputation: 502

Using static function variable vs class variable to store some state

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:

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)

Upvotes: 5

Views: 745

Answers (1)

John Zwinck
John Zwinck

Reputation: 249592

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.

Upvotes: 5

Related Questions