синглтон майерса и многопоточность

265
27 ноября 2017, 18:55

здравствуйте, не раз слышал фразу, что "после c++11 синглтон майерса стал потокобезопасным"... можете объяснить почему такой код вдруг стал потокобезопасным?

class singleton
{
public:
   static singleton* instance() {
   static singleton inst;
   return &inst;
}
private:
  singleton() {}
};
Answer 1

Это гарантируется стандартом, а именно [stmt.dcl]p4, стандарта C++17 (11 версии под рукой нет).

Dynamic initialization of a block-scope variable with static storage duration (6.7.1) or thread storage duration (6.7.2) is performed the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization. If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.

Минусы подобного подхода мне не известны. Довольно удобный метод создания одиночки.

READ ALSO
Не удаётся открыть файл с помощью std::ifstream

Не удаётся открыть файл с помощью std::ifstream

Привет, не найду костыльХочу свою функцию для чтения/записи файлов, но оно не хочет считывать

324
Доступ к структуре через unsigned char

Доступ к структуре через unsigned char

Пусть есть структура S следующего вида:

329
strict aliasing и реальные компиляторы

strict aliasing и реальные компиляторы

Сразу же оговорюсь: я уважаю стандарт :) "Закон есть закон" (с) Фердинанд Пасторелли

223