|
Boost : |
From: CHAOS (0xchaos_at_[hidden])
Date: 2005-01-05 16:00:42
Dave Handley wrote:
> Ordering of Singletons is, in my opinion, one of the most important issues with Singletons. It is almost certainly insufficient in most applications to create in a specific order, and delete in reverse order. One reason for this is start-up performance - you don't want every Singleton to have to create at startup (necessarily). Another reason can be memory efficiency. Loki again provides a number of policies including a Phoenix Singleton and a Longevity managed singleton. I personally tend to use Longevity managed singletons linked to the at_exit function. Nevertheless, there are some additional things that I would like to see - for example, a phoenix singleton that could be created and destroyed more than once during a program run could be useful - either explicitly or even if not used for a while. Also, allowing thread-safety as an option is also crucial.
The way that my design works is to use reference counting in the form
of dependency objects, which create the singleton when the first
dependency is constructed and destroy the singleton when the last
dependency is destroyed. If a singleton A owns a dependency on
singleton B, that dependency lifetime will be greater than the
lifetime of A itself, meaning that B will exist for the duration of
A's lifetime.
The only property of my singleton that forces it to be constructed
before main and destructed after is the existence of a static
dependency in the singleton class to itself. If I removed this static
dependency, it would allow for singletons that could be created and
destroyed any number of times, and lifetime would be completely
controlled by the scope at which the dependencies lived.
Implementing this change would make it possible for GetInst to fail,
when it would be more desirable to have GetInst somehow utilize a
dependency itself. Perhaps I could enable this by having GetInst
return a type of smart pointer, which would own a singleton dependency
as well as pointing to the singleton object. Thoughts / suggestions?
I have no experience in dealing with thread safety. Would ensuring
thread safety require that the singleton have access to a threading
library, or would it be possible to just write the code more carefully
to ensure safety, similar to writing exception safe code?
In addition, I have no familiarity with the other design patterns you
mentioned, nor with Loki. I learned about the singleton concept
through a friend and thought that it made for an interesting
challenge. I just ordered Modern C++ Design, so hopefully I can
familiarize myself with these topics in the near future.
For reference, I will leave a link to the code below:
http://www.ezequal.com/chaos/libs/singleton.h
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk