Thread safe lazy construction of a singleton in C++

后端 未结 9 1532
梦毁少年i
梦毁少年i 2020-11-29 19:22

Is there a way to implement a singleton object in C++ that is:

  1. Lazily constructed in a thread safe manner (two threads might simultaneously be the first user o
相关标签:
9条回答
  • 2020-11-29 19:52

    You could use Matt's solution, but you'd need to use a proper mutex/critical section for locking, and by checking "pObj == NULL" both before and after the lock. Of course, pObj would also have to be static ;) . A mutex would be unnecessarily heavy in this case, you'd be better going with a critical section.

    OJ, that doesn't work. As Chris pointed out, that's double-check locking, which is not guaranteed to work in the current C++ standard. See: C++ and the Perils of Double-Checked Locking

    Edit: No problem, OJ. It's really nice in languages where it does work. I expect it will work in C++0x (though I'm not certain), because it's such a convenient idiom.

    0 讨论(0)
  • 2020-11-29 19:53

    I suppose saying don't do this because it's not safe and will probably break more often than just initializing this stuff in main() isn't going to be that popular.

    (And yes, I know that suggesting that means you shouldn't attempt to do interesting stuff in constructors of global objects. That's the point.)

    0 讨论(0)
  • 2020-11-29 19:54

    You can't do it without any static variables, however if you are willing to tolerate one, you can use Boost.Thread for this purpose. Read the "one-time initialisation" section for more info.

    Then in your singleton accessor function, use boost::call_once to construct the object, and return it.

    0 讨论(0)
提交回复
热议问题