Re: Singletons and destructors
On Jul 24, 3:10 pm, JoshuaMaur...@gmail.com wrote:
On Jul 24, 12:58 pm, Greg Herlihy <gre...@mac.com> wrote:
Why call "new" to allocate the singleton in the first place? Wouldn't
the more obvious solution be to avoid "new" and "delete" by having the
singleton be statically - instead of dynamically - allocated? In fact,
the "classic" singleton pattern takes such an approach:
I'd suggest seeing the FAQ, and the static deinitialization order
fiasco. As others have said in this thread, it's not a simple problem
with a simple solution, especially in multithreaded environments.
Anyone who follows your suggestion and reads the C++ FAQ - will learn
that there is no such thing as the "static deinitialization order
fiasco" in C++ (at least as far as the FAQ is concerned). After all,
the destruction of static objects is well-defined (static objects are
destroyed in the reverse order of their construction.)
Perhaps you are referring to what the FAQ calls C++'s "static -
initialization- order" fiasco (in which the order that statically-
allocated objects are initialized - is not always specified in C++).
However, there is no such problem with the timing of the singleton's
initialization in the sample program I posted. The singleton in that
program is certain to be initialized the very first time instance() is
called - which is exactly the same point of initialization as in the
original program.
There are other ways to show that the sample program I posted is
sound. Logically, if it is safe for the program to delete the
singleton object before main() exits, then it must also be safe to
delete that same singleton, at a later point - namely, after main()
exits. The danger is deleting an object too early, there is no danger
in deleting an object "too late". Furthermore, in a multithreaded
environment, deleting the singleton object after main() exits (that
is, after all the other threads have terminated), clearly makes the
most sense.
Of course all of these points are purely academic - I could have
simply pointed out that the singleton object is the only statically-
allocated object in the program I posted. Whereas - a program would
have to declare two or more statically-allocated objects - before it
could even begin to have a problem with the order in which they are
initialized.
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]