lundi 21 décembre 2015

Singleton instance as static field vs. static variable in getInstance() method

In this thread, the following is said about singleton instances:

The static variable can be static to the GetInstance() function, or it can be static in the Singleton class. There's interesting tradeoffs there.

What are these trade-offs? I am aware that, if declared as a static function variable, the singleton won't be constructed until the function is first called. I've also read something about thread-safety, but am unaware of what exactly that entails, or how the two approaches differ in that regard.

Are there any other major differences between the two? Which approach is better?

In my concrete example, I have a factory class set up as a singleton, and I'm storing the instance as a static const field in the class. I don't have a getInstance() method, but rather expect the user to access the instance directly, like so: ItemFactory::factory. The default constructor is private, and the instance is allocated statically.

Addendum: how good of an idea is it to overload operator() to call the createItem() method for the singleton, such that Items can be created like so: ItemFactory::factory("id")?

Aucun commentaire:

Enregistrer un commentaire