Is Meyers' implementation of the Singleton pattern thread safe?

前端 未结 6 842
我寻月下人不归
我寻月下人不归 2020-11-22 04:55

Is the following implementation, using lazy initialization, of Singleton (Meyers\' Singleton) thread safe?

static Singleton& instance()
{
           


        
6条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 05:23

    As MSalters said: It depends on the C++ implementation you use. Check the documentation. As for the other question: "If not, why?" -- The C++ standard doesn't yet mention anything about threads. But the upcoming C++ version is aware of threads and it explicitly states that the initialization of static locals is thread-safe. If two threads call such a function, one thread will perform an initialization while the other will block & wait for it to finish.

提交回复
热议问题