Re: A constrained singleton sanity check
stevewilliams2...@comcast.net wrote:
I am attempting to create a singleton, and was wondering if
someone could give me a sanity check on the design - does it
accomplish my constraints, and/or am I over complicating
things. My design constraints/environment are as follows:
1) Everything is single-threaded during static initialization (as in
prior to the open brace of main)
2) The environment may be multi-threaded during nominal program
execution (within {} of main)
3) I want a guaranteed destructor call to the singleton (excluding
exceptions, or other abnormal circumstances).
4) Other static (and/or) global objects may access the singleton
during their destructors.
Do you ever actually need both 3 and 4 in the same program?
The real kicker I was working to accommodate for above is #4.
4 is easy. So is 3. Both together become very difficult, if
not impossible.
The Idea I had was to basically hand out reference-counted
containers for the singleton. The tricky part was giving the
guarantee that static/ global objects could reference the
singleton in their destructors. The idea was that even after
{} main exits, the reference count is reduced to zero and the
singleton is destroyed, but some object's destructor could
still ressurect the singleton by asking for an instance (which
would presumably be destroyed again shortly after the local
use of that reference was destroyed).
But a resurected singleton isn't the same instance as the
original singleton. If you resurected, it's not really a
singleton anymore.
Note that your code may cause multiple creations during program
start-up as well. All it guarantees is that there is never more
than one instance of a singleton alive at any given time. Which
is fine if the singleton has no variable state, but if it has no
variable state, one can argue that there's no need for it to be
a singleton in the first place.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34