I need to access the static data member from the destructor, but when I exit the program, it seems that it cannot be guaranteed that it still exists! For some reason, static members are destroyed while there are still outstanding class instances. This is strange because I have never heard the advice “Never get static elements from a destructor” before, and yet I think I know about such a restriction, if it exists.
I will give a specific 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 that seemed to work, although when I think about it, I don't think this is 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;
};
, MyClass m_instances, m_switch? m_switch , m_alive "" , , "true" ( , ).
- ? , - .