Quantcast
Channel: Cocos Forums - Latest topics
Viewing all articles
Browse latest Browse all 17070

Correct way to implement Singleton

$
0
0

@Levis wrote:

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.

Posts: 4

Participants: 3

Read full topic


Viewing all articles
Browse latest Browse all 17070

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>