Thread safe lazy construction of a singleton in C++

后端 未结 9 1557
梦毁少年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:35

    While this question has already been answered, I think there are some other points to mention:

    • If you want lazy-instantiation of the singleton while using a pointer to a dynamically allocated instance, you'll have to make sure you clean it up at the right point.
    • 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.

    But as already stated, you can't guarantee threadsafe lazy-initialisation without using at least one synchronisation primitive.

    Edit: Yup Derek, you're right. My bad. :)

提交回复
热议问题