vendredi 27 janvier 2017

How to ensure that a method is executed only once for the lifetime of that object?

class MyObj{

    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: 1. member variable: If I use a member variable, then other functions within MyObj can access it and change it. 2. global static variable: Can't work because first,second and third will all be checking the same variable. 3. 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!

Aucun commentaire:

Enregistrer un commentaire