I'n my "Map" class constructor I have a method that loads map data from a file, it returns true or false depending if it failed or not.
Map::Map( const std::string filePath, sf::Texture* tileset )
{
if( !loadDataFromFile( filePath ) )
{
tileMatrix = NULL;
}
this->tileset = tileset;
}
The tileMatrix is a 2D matrix that is dynamically allocated when loading a map, and the values are inserted into it.
My question started of, what should I do if the function actually fails? Then the map allocated contains no actual data to display, and when it reaches the draw of my program, it will crash due to trying to access a NULL pointer and when it crashes the stack-unwinding will not happen thus not de-allocate all my memory allocated. How do most
I want to exit the program when map loading fails and de-allocate all my memory, this happens quite deep into the program flow that it's going to be hackish for it to reach the main's return.
How do people deal with these kinds of loading? Should I make an method in the map-class that returns true or false, like:
/* Somewhere inside my game-class loading */
void Game::run()
{
maps.push_back(new map("map001.map") );
maps.push_back(new map("map002.map") );
maps.push_back(new map("map003.map") );
maps.push_back(new map("map004.map") );
maps.push_back(new map("map005.map") );
for(int i = 0; i < maps.lenght - 1; i++)
if(!maps.initialized())
{
std::cout << "A map failed to load correctly" << std::endl;
return;
}
/* Game Loop, and other Code */
}
Or is their a more preferred way to deal with these kinds of errors deep inside the code?
Does this work?
int main()
{
try
{
Game game("Awesome Game");
game.run();
}
catch(...)
{
return -1;
}
return 0;
}
Can I do "throw "Couldn't load map" << std::endl;" inside the Map-class constructor? Would it catch it even if it's not directly called by the Game class but a class within the game class? Will it trigger stack-unwinding?