Re: A few questions about singletons...
On Sep 25, 1:05 am, Michael Doubez <michael.dou...@free.fr> wrote:
You can use a Meyer singleton which solve the initialisation order
issue:
static CSingleton& GetInstance()
{
CSingleton static_instance;
return static_instance;
}
And the cleanup is made at termination. The cleanup of a singleton is
delicate because you don't known how is currently using it (it is even
worse when in a DLL); you should let the system decide when it is no
longer needed.
Suffice to say, actually suggesting the simplest Meyer's singleton is
bad advice. Frankly, I've made so many mistakes on this topic recently
that I'll just point you to the thread where someone more
knowledgeable than me suggests more correct ways to do this.
http://groups.google.com/group/comp.lang.c++/browse_thread/thread/bca4044f4=
0befc6a#
1- Your singleton may cause static deinit issues. If you can leak it,
just leak it. Otherwise, it'll work correctly if all other statics
call getSingleton in their constructors. This will guarantee correct
destruction order, Last In First Out.
2- It's not thread-safe. There's the simple ways to do this correctly
which come with the caveat that "No nontrivial threads during static
init". Alternatively, use the more complex designs of Chris M.
Thomasson, which just guarantee single correct construction with
minimal overhead. There are several, depending on platform, and
exactly what guarantees you want.
Short version: Actually doing a correct singleton in C++ is hard (tm).
It requires you to understand many nuances of the language, and things
outside the language, like static initialization order fiasco, static
de-initialization order fiasco, deep knowledge of thread-safety, etc.
As long as I'm here, I might as well suggest this excellent paper as
well, which covers the more common pitfall I've seen regarding
singletons, and more generally a lack of understanding of modern real-
world threading.
http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf