Hi, I'm relatively new to C++. I wrote up a short program that uses the SFML library (the problem seems to be unrelated to it, though), but it doesn't act as intended. Could you guys help me with my problem?
The issue seems to lie in my two files GameManager.h and GameManager.cpp:
This is GameManager.h:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
#include <SFML/Graphics.hpp>
#include "Thing.h"
class TextureManager{
std::map<std::string, sf::Texture*> textureManager;
public:
TextureManager()
:textureManager()
{}
sf::Texture* loadTexture(const std::string& filename);
};
class GameManager{
static std::vector<Thing*> thingList;
static TextureManager textureManager;
public:
static Thing* createNewThing(const std::string& spriteFilename);
};
|
And GameManager.cpp:
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
|
#include <SFML/Graphics.hpp>
#include "GameManager.h"
TextureManager GameManager::textureManager = TextureManager();
std::vector<Thing*> GameManager::thingList = std::vector<Thing*>();
sf::Texture* TextureManager::loadTexture(const std::string& filename){
std::map<std::string, sf::Texture*>::iterator result = textureManager.find(filename);
if(result==textureManager.end()){
//we have not created this image yet
sf::Texture* image = new sf::Texture();
if(!image->loadFromFile(filename)){
return NULL;
}
textureManager[filename] = image;
return image;
}
else{
//we have created this image before
return result->second;
}
}
Thing* GameManager::createNewThing(const std::string& spriteFilename){
return new Thing(new sf::Sprite(*GameManager::textureManager.loadTexture(spriteFilename)),spriteFilename);
}
|
When the line "Thing* thing1 = GameManager::createNewThing("abc.gif");" is run through this code, the program seems to hit a bad state where TextureManager::textureManager is undefined when I enter TextureManager::loadTexture() (but GameManager::textureManager and GameManager::thingList seem to be fine). Specifically, VS2012 says that it has a very, very large size (about 10-20 million) with garbage data inside. And when I run this line of code, it also changes the filename variable and puts garbage data into it, despite the fact that (I think) it shouldn't do that. Eventually, the program hits an exception. My computer even crashed while running it, once, although I'm not sure whether that's due to this program or another program. I'm not sure what the problem could be; I thought that I've covered all my bases in terms of initialization of TextureManager. Could someone help me?
As an aside, if I'm making any egregiously bad coding faux pas, it would be nice if those could be pointed out; I'm still in the process of learning how to put things together into multiple files and with the usage of static/const in code.