Double lock check for shared pointers

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?

+4
2

++. - , , :

A& A::instance() {
    static A a;
    return a;
}

100% ++ 11 .

: - .

, . , , g_a , g_a. .

+1

, . , ?:

, -, - , , , , .

++ 11 std::shared_ptr, atomic_load atomic_store , ; ++ 11, static, .

+2

All Articles