Re: Threadsafe singletons
David Barrett-Lennard wrote:
Gene Bushuyev wrote:
"David Barrett-Lennard" <davidbl@iinet.net.au> wrote in message
news:1154313829.569314.297530@p79g2000cwp.googlegroups.com...
[...]
The GetInstance() function employs the lazy creation
approach. However, the intention is not to avoid
consuming resources. In fact the static InitMySingleton
instance is used to force the singleton to be eagerly
initialized before main() begins.
You don't have any guarantee that either one of your objects
is itinitialized before main (3.6.2/3). The standard only
requires that they are initialized before the first use,
neither static MySingleton nor s_init are used before main()
in your example.
I think that's a shame. I like to be able to have code
knowingly run before main() begins. For example, to allow
factories to self-register with a singleton factory registry.
You're not alone.
Do you know of any compilers that don't execute the s_init
constructor before main()?
There aren't any (supposing static linking, of course). And
there won't be, for two reasons:
1. the auto-registration idiom has become a more or less
standard idiom, enough so that no compiler vendor would risk
breaking it, and
2. if the compiler defers initialization until after main, IT
(and not the user) must solve the order of initialization
problems. Which is decidedly non trivial in the general
case, and probably impossible in cases where there are
circular dependencies (and the standard makes no exception
for circular dependencies).
So although the standard doesn't guarantee it, I depend on it,
and I'm not worried about it not working in future compilers.
--
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]