Why can't I print out my std::string vector?

Started by
18 comments, last by BiiXteR 7 years, 8 months ago

Should I still not do this even if many other classes needs MapManager? (sorry for the super late reply...)



You've fallen for the most common misuse of the singleton pattern. The singleton is there is ensure a single instance of an object, not a single point of access.

Everyone who misuses a singleton in this fashion says the same thing: "I don't want to pass my X/Manager/God/Controller/Whatever object everywhere". As @Álvaro said, at least then your dependency is obvious.

If you find that you're passing a certain object everywhere down through layers of code, this is a code smell and a sign that you should refactor your code.

That said, sometimes a global really is the lesser evil. Things like a log object for example.

But let's say you look at your options and you decide that it really would be less painful to not pass MapManager everywhere. In that case, just create a global and own that decision.

You have you MapManager class defined as normal (MapManager.h/.cpp). These files should know nothing about the global, otherwise you can't use them without it.
Create a header where you will declare your global MapManager

Globals.h


#include "MapManager.h"

// namespaces are great!
namespace InsertGameNameHere
{
   namespace Globals
   {
      // the global map state
      extern MapManager TheMap;
   }
}

Then in your main.cpp instantiate TheMap


#include "Globals.h"

// instantiate the map. this should be in exactly one place in the code
MapManager InsertGameNameHere::Globals::TheMap;

int main()
{
   InsertGameNameHere::Globals::TheMap.DrawMap();
   // do more stuff
}

Anywhere else you need to access the map, just include Globals.h without instantiating the map.

Monster.cpp


#include "Globals.h"

namespace InsertGameNameHere
{
    void SpawnMonster()
    {
       Monster monster;
       monster.SetPosition(Globals::TheMap.GetRandomSpawnPoint());
       // etc.
    }
}
  

Alright, I'll go ahead and replace my singletons with that instead.

I'll read up some more on singletons as well.

Thanks for the help :)

This topic is closed to new replies.

Advertisement