I need to access a static data member from a destructor, but on program exit it seems that it cannot be guaranteed to still exist! For some reason, the static members are being destroyed whilst there are still outstanding instances of the class. It's odd because I've never heard the advice "Never access static members from a destructor" before, and yet I think I'd know about such a limitation if it existed.
I'll give a concrete example:
class MyClass {
public:
~MyClass() { m_instances.erase(m_name); }
private:
long m_name;
static std::map<long, MyClass*> m_instances;
};
In another class, I tried the following nasty hack which appeared to work, though when I think about it I don't think it's really a solution at all.
class MyClass {
friend class Switch;
public:
~MyClass() { if (m_alive) m_instances.erase(m_name); }
private:
static bool m_alive;
class Switch {
~Switch() { MyClass::m_alive = false; }
};
static Switch m_switch;
long m_name;
static std::map<long, MyClass*> m_instances;
};
What if an instance of MyClass is destroyed after m_instances but before m_switch?? And even if m_switch dies first, the boolean m_alive might have been "destroyed" and therefore possibly overwritten to 'true' (unlikely, I know).
So can anyone offer a better solution? I expect I am missing something very obvious here.