c++concurrencystatic-initialization

call_once over local object's static initialization


I've gone through this question on when to use call_once and this regarding thread safety of static initialization. It appears that if a local callable is statically initialized, it serves pretty much the same purpose. What nuances/design considerations should be factored in while choosing one over the other? Here's the specific use case that I'm having where we just want to log something once (full compiling example).

void fooCallOnceVersion() {
    static std::once_flag once;
    std::call_once(once, []() {
        std::printf("Foo call once\n");
    });
}


void fooStaticVersion() {
    static auto printLog = []() {
        return std::printf("Foo static version\n");
    }();
}

Solution

  • In your fooStaticVersion you had to invent a value to be stored. This can be considered a hack while std::once_flag is properly documented. In your limited example, I am not aware of important differences other than that.

    However, the std::once_flag can be stored elsewhere and allows multiple different calls to std::call_once. For example:

    class foo {
         std::once_flag flag;
         void bar1(auto&& f) { std::call_once(flag,f); }
         void bar2(auto&& f) { std::call_once(flag,f); }
    }
    

    You cannot easily simluate the same with a static variable, because it would be the same for all instances.