In C++11, the following is thread-safe:
void someFunc()
{
static MyObject object;
}
But what about
void someFunc()
{
static MyObject *ptr = new MyObject();
}
Is this then thread-safe or not?
As it was mentioned in the comments by @Nawaz, it is possibile, that the MyObject constructor isn't thread-safe, so let's divide the question into parts:
1) If the ctor is thread-safe (it doesn't access any shared state), is this static MyObject *ptr = new MyObject();
thread-safe? In other words, is static int *ptr = new int(0);
thread-safe?
2) If the ctor isn't thread-safe, but the object is created only by calling someFunc
from different threads, and the constructor is never used from anywhere else, will this be thread-safe then?
Yes, it is thread-safe. This follows from the same guarantee that applies to the first example, which is that concurrent executions of the function will initialize the static variable exactly once. Since the static pointer must be initialized exactly once, and the way to initialize it is defined as a call to new
, then new
and the constructor it invokes will each be called exactly once. Assuming that the constructor of the new
object does not do anything unsafe, the whole thing will be safe.
Thanks to Matthieu M. for pointing out one exception: if the initialization throws, it will be attempted again by the next (pending or future) invocation of the function. It's still thread-safe though, because the second attempt will not begin until after the first one failed.
That being said, it's worrisome to see such code, because it seems likely to result in a memory leak which may be flagged by automated tools like valgrind, so it would be better to avoid this somehow. Even a class with a static member might be better, in that it would then be easier to clean up the static with a special method to be invoked before the program ends.
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