Function level static variable NOT static for lazy book keeping

86 views Asked by At

I want to use a function level variable for book keeping since I do not want to pollute my code with a ton of member variables like this:

class A
{
void funcA() {
    // ...
    static int oldValue = -1;
    if (oldValue != newValue) {
        loadNewData();
        oldValue = newValue;
    }
}
};

But I need the variable oldValue to be not static to have a unique check for each instance of this class. Is there a way to use this lazy instantiation of a book-keeping variable but on a per-instance level?

2

There are 2 answers

0
fsb On

There isn't a way to use a non-static variable in a function scope and use it to track previous values assigned in previous invocations. A regular variable will just be assigned -1, as in your example, and will sequentially hold the values of the assignments that follow (as you seem aware).

Your case is precisely the case when to use instance variables, since you need private mutable state associated to a certain method's content. You might even say it is the case for an instance variable by an OO definition/approach.

It is also easy to provide a lazy initializer for an instance variable in a getter, encapsulating that same initialization logic for every method that uses it.

While there might be other methods to work around the problem, they don't seem like the cleanest solution.

0
srinivas reddy On

I did not try but probably the following would work.

Instead of a single Variable , use a static array/List with an other variable which counts the instance number.