Re: Is this safe?
"Joshua Maurice" <joshuamaurice@gmail.com> wrote in message
news:c1847df1-b4d7-4726-b8ae-a3332722652f@n16g2000yqm.googlegroups.com...
On Jun 30, 11:46 am, mattb <matthew.b...@l-3com.com> wrote:
I have come across a singleton implementation of the following form in
some code I have to maintain...
[Out of order quote]
Is this safe?
Not in the slightest.
file - Singleton.h
#ifndef SINGLETON_H
#define SINGLETON_H
You may want a more unique name for the macro, something involving
your company name for example. I'd imagine SINGLETON_H would be a
common name.
Also, "xxx.hpp" is the way of C++, not "xxx.h". Just a stylistic
nitpick.
template<class T>
{
public:
static T& instance()
{
if ( !instance_ )
{
AccessLock<CriticalSection> access(key_);
if ( !instance_ )
{
static Singleton<T> theInstance;
instance_ = &theInstance;
}
}
return instance_;
}
See "C++ and the Perils of Double Checked Locking"
http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf
for a thorough description of why the above does not work and has
never worked.
[...]
If `instance_' is declared as volatile, it works fine in MSVC 8 and higher.
Those compilers automatically insert the proper memory barriers on
architectures which require them (e.g., PPC). You can also get it to work
perfectly fine if you code it in assembly language and add the proper
barriers manually.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]