Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Have you considered what would happened if your singleton wasn't deleted at all?</p> <p>By definition, a singleton is an single object shared by many client objects as the clients tend to come and go. Most of the time your singleton will live as long as your process.</p> <p>When your process shuts down, OS will reclaim most resources (memory, file handles, sockets...) and it is perfectly normal to allocate that singleton and then just let it die. This would be my recommendation.</p> <ol> <li>The code is simpler. Less function calls, less complexity. No need to consider when terminate should be called and that's what brought you here.</li> <li>With explicit cleanup, as your application becomes more complex (and they tend to as you keep adding features), you introduce the risk that some other object will attempt to access singleton reference after it was terminated and destroyed. Now instead of harmless memory leak which gets wiped up by the OS immediately, you have an ugly unhandled exception dialog that your users get to look at. </li> </ol> <p>It is also a good practice to put Initialize() function for the singleton inside GetInstance() (as pdillon3 demonstrated) instead of having your application explicitly call Initialize(). You didn't specify this part, and if your project is an executable, you should be ok with existing design. But just be careful if you put this code inside a DLL. Some people assume DllMain is a good place to initialize singleton objects and it's not. During DllMain, loader lock global critical section is locked and singleton initializations tend to cause all kinds of trouble.</p> <p>Plus now instead of 3 methods in your singleton interface, you are down to just one: GetInstance(), nice and simple.</p> <p>Lastly, as Dietmar mentioned (although I still consider Singleton to be a pattern, not an anti-pattern and <a href="http://en.wikipedia.org/wiki/Design_Patterns" rel="nofollow">GoF</a> agree with me), you should really consider whether or not you actually need a singleton. I use them from time to time, but only when I have no choice, not because they are convenient. They really are a design pattern of last resort when alternative is even more evil. Don't use them just because they are convenient.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload