how to answer this question?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
EDIT:
Oops, the answer no. As others have pointed out, simply setting all methods/members to static follows the Monostate pattern (of which I was not aware). I was too eager to show off my shiny Singleton template (a simplified version of Alexandrescu’s SingletonHolder, really).
This answer should be downvoted.
Original Answer:
Yes. But it is less flexible than other ways of designing singletons. See Modern C++ Design by Alexandrescu and his Loki library: http://en.wikipedia.org/wiki/Loki_%28C%2B%2B%29
If you have several static singletons that depend on each other and on other global objects, you risk having problems because the order of their initialization (before main() kicks in) is tricky and can lead to unexpected results.
Using templates, you can convert normal classes into singletons. If you later decide that your singleton is no longer a singleton (i.e. you can have multiple instances), then you don’t have to convert all the class’s methods to non-static.
One way, using templates, is something like this:
Note that this does not prevent you from creating Foo instances, unless you make the Foo constructor private (and make Singleton a friend of Foo).
An advantage with this method over all-static classes is that you have more control over when the singleton object is constructed. It’ll be constructed the first time you access the singleton. So you can have something like this:
There is debate over of the appropriateness of Singletons. Some say they are global objects in disguise and can make your code less reusable. I will not comment further on that, as I have not made up my mind myself.
EDIT:
If you find TheFoo::instance() too verbose, you can always provide an inline shortcut function or use references:
Mmmm…. off to make coffee & sandwich.