This question has been asked in a C++98 context, and answered in that context, but nothing was clearly stated about C++11
const some_type& create_const_thingy()
{
lock my_lock(some_mutex);
static const some_type the_const_thingy;
return the_const_thingy;
}
void use_const_thingy()
{
static const some_type& the_const_thingy = create_const_thingy();
// use the_const_thingy
}
Would this initialization pattern ensure that:
create_const_thingy
is called only onceThanks in advance!
Since C++11 all static local variables are guaranteed to be initialized only once in a thread-safe manner.
As per cppreference:
If multiple threads attempt to initialize the same static local variable concurrently, the initialization occurs exactly once (similar behavior can be obtained for arbitrary functions with
std::call_once
). Note: usual implementations of this feature use variants of the double-checked locking pattern, which reduces runtime overhead for already-initialized local statics to a single non-atomic boolean comparison.
So, for your questions:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With