title: Static object with access to static member in the destructor
body: <p>I'm trying to implement the following behavior (simplified):</p>
  
  <ul>
  <li>There's an Object base class that anyone can derive from and there will be several instances of these.</li>
  <li>Anyone from anywhere can add an instance pointer to a globally accessible set of pointers to Object.</li>
  <li>An object should remove itself from that set (if it's in it) upon destruction.</li>
  <li>I only need it to work in a single thread and in a single module (no dynamic library loading etc.)</li>
  </ul>
  
  <p>Conceptually something like this:</p>
  
  <pre><code>class Object {
  public:
  //...
  
  ~Object() { reg.erase(this);  }
  static void register(Object* obj) { reg.insert(obj); }
  
  static std::set&lt;Object*&gt; reg;
  }
  </code></pre>
  
  <p>This is simplified, as it's not really a set but a more complicated container. As a result there are some iterators etc. involved in the register() and the destructor. I also omitted getters/setters and access control for brevity.</p>
  
  <p>The problem I have with this is that it works as long as no one creates a static Object (or derived). It will then depend on the actual order of destruction of the static set and the static object (which is undefined if I'm not mistaken). I tested that it really crashes or not, depending on the order of these two. I can't(and don't want to) guarantee that no static instance of Object will be created. I also don't want to enforce user of the class to call any cleanup code etc. Object should be "self aware".</p>
  
  <p>I tried to employ singleton for the set but I keep circling back to the same chicken and egg problem with statics in the destructor.</p>
  
  <p>How can I either fix this or achieve the same behavior with another design (possibly without so much statics)? Maybe there's a way to ensure that a particular static will be destroyed after anything else (at least in "my" code)?</p>