class MyObj{
public:
void myFunc(){
//ToBeExecutedJustOnce
}
};
I have a function that I want to be executable only once for the lifetime of MyObj
. There may be many instances of MyObj
, and each should be able to execute that function once. So if I have:
MyObj first;
MyObj second;
MyObj third:
first.myFunc(); // Should execute
second.myFunc(); // Should execute
third.myFunc(); // Should execute
first.myFunc(); // Should not execute
second.myFunc(); // Should not execute
third.myFunc(); // Should not execute
Options:
- member variable: If I use a member variable, then other functions within
MyObj
can access it and change it. - global static variable: Can't work because first,second and third will all be checking the same variable.
- local static: Same problem as #2.
The only solution I have found, is to have MyObj
inherit from another class
MyOtherObj{
private:
bool _isInit = false;
public:
bool isInit(){
bool ret = true;
if (!_isInit){
ret = false;
_isInit = true;
}
return ret;
}
};
class MyObj : public MyOtherObj {
public:
void MyFunc(){
if (!isInit()){
//Do stuff...
}
}
};
Any better suggestion ?
EDIT: I don't care about thread safety!
EDIT: I do not want to execute the method in the constructor, simply because the method may need to be executed much later in the lifetime of the object....