| | | | | |

The Dead Reference Problem

  • Circular Singleton Interactions: KDL
    1. Keyboard and Display singletons created
    2. Log records errors, including errors in constructing/destroying K and D
    3. First error instantiates L, registers it for destruction ...
  • Illustrates that when multiple singletons interact, we cannot ensure correct order of destruction
  • At least: detect the dead reference
  • // Singleton.h
    class Singleton
    {
    public:
      static Singleton& Instance()
      {
        if (!pInstance)
        {
          if (destroyed)  // check for dead reference
            OnDeadReference();
          else            // create on first call
            Create();
        }
        return *pInstance_;
      }
      virtual ~Singleton()
      {
        pInstancce_ = 0;
        destroyed_ = true;
      }
    
    private:
      static void Create()
      {
        static Singleton theInstance;
        pInstance_ = &theInstance;
      }
      static void OnDeadReference()
      {
        throw std::runtime_error("Dead Reference Detected");
      }
      // variables
      static Singleton* pInstance_;
      static bool       destroyed_;
      // disabled constructors, assignment
      ...
    };
    
    // Singleton.cpp
    Singleton* Singleton::pInstance_ = 0;
    bool       Singleton::destroyed_ = false;
    

| | Top of Page | 9. Singletons - 6 of 18