When using SDL, I have been handling errors (e.g. during SDL initialisation) by returning false whenever an error is encountered in a function, and true otherwise. The cleaning-up is then performed by calling a close() function at the very end of the main() function, as such:
int main(){
if(!init()){
// do some stuff
}
...
close();
return 0;
}
close() function:
void close(){
SDL_DestroyRenderer(g_Renderer);
SDL_DestroyWindow(g_Window);
IMG_Quit();
SDL_Quit();
}
However, I have realised that this method of cleaning-up means I can't really throw an exception, as close() function would not be called.
After doing a bit of reading around, I have decided that I would try not to throw exceptions, unless needed, for performance-related reasons (I heard that this is important, especially in game development).
Also, this would mean I need to add more functions for cleaning up onto close() as the program grows, which seems impractical and easy to forget.
So the questions I have are:
- In general, when should we raise exceptions when using SDL? Is it considered good practice to generally avoid them unless needed?
- In order to allow for uses of exceptions, how should SDL resources be cleaned up? I have looked at some approaches, but I'm not sure when I would use each one, or combine each approaches:
- Create a C++ wrapper class to handle both initialisation in the constructor and cleaning up in its destructor
- Use
unique_ptr(or other smart pointers) by initialising SDL object normally and provide a deleter class for cleaning-up. - Use
atexit()to handleSDL_Quit()andIMG_Quit()?
I was thinking of implementing a wrapper class, but then realised I would probably need to throw an exception in case of error during initialization, e.g. from SDL_CreateWindow(),which I'm trying to avoid. Any help or advice?