I have two singletons, the first one’s header looks like this (I’ve omitted everything that is not related to the Singleton pattern):
#ifndef TEXTUREMANAGER_DEFINED_H
#define TEXTUREMANAGER_DEFINED_H
class FontManager;
class TextureManager
{
private:
static TextureManager *instance;
TextureManager();
public:
FontManager *fontManager;
static TextureManager* Instance();
};
#endif
And in the implementation, this is the Instance() method (and the initialization of the instance static member):
#include "FontManager.h"
TextureManager * TextureManager::instance = 0;
TextureManager* TextureManager::Instance ()
{
if (instance==0)
instance=new TextureManager;
return instance;
}
And this is the constructor:
TextureManager::TextureManager()
{
fontManager=FontManager::Instance();
}
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?
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 if (instance==0) always evaluated to true.
Because you’ve written an infinite loop where the constructor of
TextureManagercalls the constructor ofFontManagerwhich then calls the constructor ofTextureManager…. and so on.Because the constructor has to complete before the static variables are assigned you’ll end up in this loop.