Disclaimer: I come from the Java background, and therefore I don’t know how many internal C ++ components (and related libraries) work.
I read enough to know that double-check locking is evil, and the correct and safe implementation of a singleton pattern requires appropriate tools.
I believe that the following code may be unsafe, given the reordering of the compiler and the assignment of uninitialized objects, but I'm not sure that I am missing what I do not understand about the language.
typedef boost::shared_ptr<A> APtr;
APtr g_a;
boost::mutex g_a_mutex;
const APtr& A::instance()
{
if (!g_a)
{
boost::mutex::scoped_lock lock(g_a_mutex);
if (!g_a)
{
g_a = boost::make_shared<A>();
}
}
return g_a;
}
I believe the actual code compiled under C ++ 03.
Is this implementation unsafe? If so, how?