I have a static member variable in a class:
template <class T>
class classFactory
{
...
public:
...
typedef std::map<KeyType, Creatory> Creator;
...
private:
...
static Creator &GetCreators()
{
static Creator creator;
return creator;
}
}
An exit()->atexit() was called on the main() function which called a global destructor and deleted this static member creator.
another thread was still accessing this static member using the same GetCreators() function and caused a crash.
My question:
Where is this static member allocated? I know it is an uninitialized global so it should go on BSS? But why does it get destroyed by the global destructor even when it is in the static member function?
I was told making it a new would fix this problem -> global destructor will leave it out.
i.e.
static Creator &GetCreators()
{
static Creator* creator = new Creator;
return *creator;
}
Why would this fix the problem? Because now it goes on the heap? Why would the global destructor leave this alone? In this case, when should I delete this object. I have no way of knowing which thread will be last in execution.
Now I did try making the object a thread_local but this makes many of my programs crash (this is a driver framework called by other clients).
static Creators &GetCreators()
{
thread_local static Creators creators;
return creators;
}
The reason , I think , is that the object creation becomes timing based when I make it thread_local static and causes many race conditions.