In my project, I'm working with about 4 singletons made the Scott Meyer's way. One of them:
LevelRenderer& LevelRenderer::Instance()
{
static LevelRenderer obj;
return obj;
}
Now two of those Singletons, LevelRenderer
and LevelSymbolTable
interact with each other. For example, in this method:
void LevelRenderer::Parse(std::vector<std::string>& lineSet)
{
LevelSymbolTable& table = LevelSymbolTable::Instance();
/** removed code which was irrelevant **/
// for each line in lineSet
BOOST_FOREACH(std::string line, lineSet)
{
// for each character in the line
BOOST_FOREACH(char sym, line)
{
/** code... **/
// otherwise
else
{
sf::Sprite spr;
// Used LevelSymbolTable's Instance here...
table.GenerateSpriteFromSymbol(spr, sym);
// ^ Inside LevelRenderer
/** irrelevant code... **/
}
}
}
}
Now, although the problem hasn't occurred yet. The thing I am afraid of is, what if the LevelSymbolTable
instance is already destroyed before I call GenerateSpriteFromSymbol
?
Since I used the Scott Meyer way, the Singleton's instance was allocated by the stack. Hence is is guaranteed to be destroyed using the last created first destroyed rule. Now if LevelSymbolTable
's Instance is created after LevelRenderer
's Instance, it will be destroyed before LevelRenderer
's Instance, right? So then, if I call a method of LevelSymbolTable
inside LevelRenderer
(especially in LevelRenderer
's destructor), I will be treading on undefined behaviour land.
As I said before, this problem hasn't actually occurred while debugging, and is purely my assumption and guess-work. So, is my conclusion correct? Is LevelSymbolTable
liable to be destroyed before LevelRenderer
. If so, is there any way out of this mess?