mercredi 30 mars 2016

Correct way to implement Singleton in Cocos2Dx

Currently I'm using this approach:

class Singleton {
public:
  static Singleton &getInstance()   {
    static Singleton *instance = new Singleton();
    return *instance;
  }
void getData();

private:
  Singleton() {}
};

In this way I can use a method from Singleton writing:

Singleton::getInstance.getData();

And this seems the right way reading a lot of tutorials for C++11. But reading through cocos Director singleton code (also FileUtils etc..), I have seen that Cocos uses this other approach:

class Singleton {
public:
  static Singleton *getInstance()   {
    instance = new Singleton();
    return instance;
  }
void getData();

private:
  Singleton() {}
  static Singleton *instance;
};

With this approach I have to write:

Singleton::getInstance->getData();

Because of the pointer *getInstance instead of reference &getInstance.

I think the difference is big, but I don't know if one way is correct and the other don't.

Please help me to sorting out this concept.

Aucun commentaire:

Enregistrer un commentaire