My friend asked me today why he prefers to use a singleton over a global static object? The way I started explaining was that a singleton could have a state against a static global object, but it wasn’t ... but then I wasn’t sure ... because it is in C ++ .. (I went from C #)
A static global object can also have state in C #:
class myclass {
What are the advantages of one over the other? (in C ++)
The syntax distorts your code, but the global static instance does not. There are countless SO questions about singleton issues already. Here is one , and another , or another .
In short, singleton gives you two things:
- globally accessible object and
- ensure that only one instance can be created.
If we want only the first point, we must create a globally accessible object. And why will we ever want a second? We do not know in advance how our code can be used in the future, so why remove the nail and remove it, which can be useful functionality? Usually we are mistaken when we predict that "I need only one instance." And there is a big difference between “I only need one instance” (the correct answer is to create one instance), and “the application cannot under any circumstances work correctly if several instances are created, format the user's hard drive and publish confidential data on the Internet” ( answer here: Most likely, your application is broken, but if it is not, then yes, one single is what you need)
jalf Sep 24 '09 at 6:59 2009-09-24 06:59
source share