It is known that static initialization order fiasco (SIOF) can be solved by using construct on first use idiom (COFU). However, this solution may introduce the issue with race conditions when the variable is being initialized from multiple threads.
I tried to avoid both SIOF and race conditions in my project in a following way. I used COFU. And I forced initialization of target variable by using non-local variable (c_unusedNonLocal
) in cpp. Thus, thanks to c_unusedNonLocal
, even if there are no non-locals which access target variable via B::getA
it is initialized anyway. What is important, it is initialized before main
in a single thread. So, with read-only access there should be no race conditions and no SIOF.
Is this a feasible solution? Are there any possible pitfalls or I mistaken about initialization in a single thread or whatever?
Thanks.
a.h
struct A
{
A() {}
};
b.h
struct B
{
static const A& getA();
};
b.cpp
// force initialization before 'main'
// assuming that this happens in a single thread (thus no race conditions)
static const A& c_unusedNonLocal = B::getA();
const A& B::getA()
{
static const A* result = new A();
return *result;
}
main.cpp
int main() {
// _read only_ access via B::getA is now thread safe
// because object is guaranteed (?) to be initialized before main
return 0;
}