"Static File" loses references. "Normal" variable works fine.

Hello everyone.

I'm currently writing a little game with SFML to get at ease with C++, and came across some kind of a problem.
I wrote a little templated "ResourceManager" class which should allow me to load all sorts of resources as long as a "Loader" is defined for it.

Since I want to make these resourcemanagers accessible everywhere, I only have a few solutions:

A1. Make them static in my main-class
I don't like this way of doing it. I recently read some articles about "uncoupling" different systems of a game, and this would just be exactly the contrary.


A2. Singleton
Apparently this is a "taboo".


A3. "Static File" (No idea how to call it)
Just some class-less members and functions, thrown into their own file. This would make them accessible everywhere by just including the file.

Doesnt seem right to me either, but I don't know any other solutions.


What I tested:

B1. I created and used my own ResourceManagers in my main-method where the game-loop is located. Everything works fine, meaning that the problem aren't my managers in itself.

B2. I created a static file (see A3), where I put my managers into. Unfortunately, this method seems to lose all the data I put into: I have a load-method and a request-method. My debug messages output me the size of an array where my data is stored. When calling load, the size increases by one. But when calling request, the size is back to 0, so something went wrong. Don't have the problem with B1.

Does anyone know why this happens? I'm pretty sure it has something to do with variable scoping, although I don't know why.

My code looks pretty much like this (Unnecessary parts excluded):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//ResourceManager.h
template<class Res> class ResourceManager {
protected:
	std::map<int, Res*> resourceList;
	Loader<Res> * loader;
public:
	ResourceManager(Loader<Res> * loader);
	void load(int key, std::string filePath);
	Res* request(int key);
};

//Loader.h
template<class T> class Loader{
public:
	T* loadFromFile(const std::string& filePath);
};

//B1, working fine
ResourceManager<sf::Sprite> spriteManager(new Loader<sf::Sprite>());
spriteManager.load(0, "something.png")
sf::Sprite * sprite = spriteManager.request(0);
...
window.draw(*sprite);

//B2, not working
/*In some file*/
static ResourceManager<sf::Sprite> spriteManager(new Loader<sf::Sprite>());
spriteManager.load(0, "something.png")
/*In another file*/
#include "Somefile.h"
sf::Sprite * sprite = Somefile::spriteManager.request(0);
...
window.draw(*sprite);


Could anyone maybe help me, please :3?

Kind regards,
Cinzedark
Topic archived. No new replies allowed.