From: souravsain on
Hi All
This is my first post to the group and am exited! Here's my question:

How and when will you delete the singleton object in a singleton
design pattern?

Thanks,
Sourav

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

From: DeMarcus on
On 2010-07-01 16:30, souravsain wrote:
> Hi All
> This is my first post to the group and am exited! Here's my question:
>
> How and when will you delete the singleton object in a singleton
> design pattern?
>
> Thanks,
> Sourav
>

You can do it in several different ways. In the book Modern C++ Design
by Andrei Alexandrescu he mentions at least four ways to handle the
lifetime of Singletons. Following is an extract from page 153 of that book.

DefaultLifetime
Manages the object's lifetime by obeying C++ rules.
Uses atexit() to get the job done.

PhoenixSingleton
Same as DefaultLifetime but allows re-creation of the Singleton
object.

SingletonWithLongevity
Assigns longevity to the Singleton object.

NoDestroy
Does not destroy the Singleton object.


Basically, the problem is not /how/ to delete the Singleton, but rather
/when/ to delete it. Since Singletons can access each other it may be
tricky to control the order of destruction.

For instance PhoenixSingleton solves it by re-create the Singleton again
if it's accessed after it has been destroyed.

SingletonWithLongevity gives each Singleton a lifetime span, so order of
destruction can be controlled.

The NoDestroy variant simply doesn't destroy the Singleton which may
lead to memory leaks and resource blocking. However, since this will
happen just before application shut down, at least the memory leaks
isn't that bad. It's worse with resource allocation that may be hanging.

I can recommend to buy the book where you will get a good insight into
how Singleton works.


HTH,

/Daniel


--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

From: Martin B. on
souravsain wrote:
> Hi All
> This is my first post to the group and am exited! Here's my question:
>
> How and when will you delete the singleton object in a singleton
> design pattern?
>

Quick answer: It depends on the singleton.

You can clean it up during global-object-destruction-phase (don't know a
better term, sorry) - that is, it is "deleted" just before the end of
you program.

You can clean it up when the last client is done using it. (For this you
can use a shared_ptr, but it tends to get a bit involved.)

Note that singletons in multithreaded environments in C++ are hard to
get right. (see "static initialization order fiasco")

br,
Martin

--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]