Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy doesn't this singleton pattern work?
    text
    copied!<p>I have two singletons, the first one's header looks like this (I've omitted everything that is not related to the Singleton pattern):</p> <pre><code>#ifndef TEXTUREMANAGER_DEFINED_H #define TEXTUREMANAGER_DEFINED_H class FontManager; class TextureManager { private: static TextureManager *instance; TextureManager(); public: FontManager *fontManager; static TextureManager* Instance(); }; #endif </code></pre> <p>And in the implementation, this is the Instance() method (and the initialization of the instance static member):</p> <pre><code>#include "FontManager.h" TextureManager * TextureManager::instance = 0; TextureManager* TextureManager::Instance () { if (instance==0) instance=new TextureManager; return instance; } </code></pre> <p>And this is the constructor:</p> <pre><code>TextureManager::TextureManager() { fontManager=FontManager::Instance(); } </code></pre> <p>The second singleton's (FontManager's) design is exactly the same, but instead of a FontManager pointer has a TextureManager pointer, and in it's constructor it initializes that pointer with TextureManager::Instance(). This should work like this: TextureManager is instanciated first (When the program starts), and in its constructor instanciates for the first time the FontManager singleton calling FontManager::Instance(). FontManager, in it's constructor, assigns its pointer to a TextureManager with TextureManager::Instance() and this method returns the TextureManager instance that already exists. Right?</p> <p>But instead of that the program enters an infinite loop because (I don't know why) the Instance() methods always create a new instance. I'ts like the <code>if (instance==0)</code> always evaluated to true.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload