Update
If we look at the draft standard section of C ++ 30.4.4.1 Struct once_flag, we can see that the constructor is defined as:
constexpr once_flag() noexcept;
since it is constexpr, your static instance will be statically initialized, and we can see an example in section 30.4.4.2 function, which uses a static instance:
void g() { static std::once_flag flag2; std::call_once(flag2, initializer()); }
Original
If we look at the documentation on std :: once_flag , it says:
once_flag(); Cnstructs an once_flag object. The internal state is set to indicate that no function has been called yet.
and if we look further at the documentation of the call_once document, we will see the following example demonstrating how to use std::once_flag :
#include <iostream> #include <thread> #include <mutex> std::once_flag flag; void do_once() { std::call_once(flag, [](){ std::cout << "Called once" << std::endl; }); } int main() { std::thread t1(do_once); std::thread t2(do_once); std::thread t3(do_once); std::thread t4(do_once); t1.join(); t2.join(); t3.join(); t4.join(); }
with the following expected output:
Called once
source share