MyClass::Foo()
{
static bool isFirst = true;
if (isFirst)
do something;
isFirst = false;
}
MyClass::Bar()
{
static bool isFirst = true;
if (isFirst)
do something;
isFirst = false;
}
I have used the above structure and it worked well so far when I worked with only one instance of the class.
The problem is all instances of MyClass seem to share the static variable.
How can I make the variable not-shared by different instances(but shared among same instance)?
Do I need to maintain a separate data structure to store instances somewhere?
Or could this be done with clever use of c++ syntax?
edit
I forgot to mention I have such variables in many functions.
Added MyClass::Bar() up there.
I hope there’s a way without defining isFirstForFoo, isFirstForBar, and so on as class member variables, because there are so many.
My actual code looks like this
BookInfoVector_t DBProcess_GET_BOOK::SelectBookList()
{
const char* query = "some query statement";
static nsl::SQLitePreparedStatement preparedStatement = nsl::SQLitePreparedStatement(static_cast<nsl::SQLiteConnection*>(mDBConnection), query);
static bool isFirst = true;
_InitializeDBProcess(&preparedStatement, isFirst);
...
}
I do some initialization on preparedStatement on first run of code, and as you can imagine, I have to define isFirst for all queries I use.
That is exactly what a
staticvariable is.You need to make
isFirsta (non-static) member ofMyClass. And rename it, following your edit:If you really “have such variables in many functions”, then I recommend you rethink the design of
MyClass. I can’t tell you how, given how vague and generic your example is but you’re almost certainly violating the Single Responsibility Principle.