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");
}();
}
In your
fooStaticVersionyou had to invent a value to be stored. This can be considered a hack whilestd::once_flagis properly documented. In your limited example, I am not aware of important differences other than that.However, the
std::once_flagcan be stored elsewhere and allows multiple different calls tostd::call_once. For example:You cannot easily simluate the same with a
staticvariable, because it would be the same for all instances.