std::call_once vs std::mutex for thread-safe initialization

后端 未结 3 1097
南笙
南笙 2021-02-05 10:16

I\'m a bit confused about the purpose of std::call_once. To be clear, I understand exactly what std::call_once does, and how to use it. It\'

3条回答
  •  心在旅途
    2021-02-05 10:44

    Slight variation on standard C++ solution is to use lambda inside the usual one:

    // header.h
    namespace dbj_once {
    
        struct singleton final {};
    
        inline singleton & instance()
        {
            static singleton single_instance = []() -> singleton {
                // this is called only once
                // do some more complex initialization
                // here
                return {};
            }();
            return single_instance;
        };
    
     } // dbj_once
    

    Please observe

    • anonymous namespace implies default static linkage for variables inside. Thus do not put this inside it. This is header code.
    • worth repeating: this is safe in presence of multiple threads (MT) and is supported as a such by all major compilers
    • inside is a lambda which is guaranteed to be called only once
    • this pattern is also safe to use in header only situations

提交回复
热议问题