Reputation: 3198
I am trying to get my program to end when the destructor of the object is called. Its part way working because the object is deleted but the program is still running. Is there any way to do this? Or is this a wrong way to do this with a better way? Thank you for all the help! Its much appreciated!
here is the main function
#include "engine.h"
int main(int argc, char* argv[]) {
bool running = true;
Engine engine;
engine.init();
while(running == true) {
engine.update();
engine.render();
}
return 0;
}
and here is the object .cpp
#include "engine.h"
Engine::Engine() {
}
void Engine::init() {
SDL_Init(SDL_INIT_VIDEO);
screen = SDL_CreateWindow("Engine", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 960, 540, SDL_WINDOW_SHOWN);
renderer = SDL_CreateRenderer(screen, -1, SDL_RENDERER_ACCELERATED);
if(screen == NULL) {
std::cout << "Could not create window: " << SDL_GetError() << std::endl;
}
}
void Engine::update(){
SDL_PollEvent(&event);
if(event.type == SDL_QUIT) {
delete this;
}
}
void Engine::render() {
SDL_RenderClear(renderer);
SDL_RenderPresent(renderer);
}
Engine::~Engine() {
SDL_Quit();
}
Upvotes: 1
Views: 136
Reputation: 42574
Using an exception is probably the most graceful way to exit from deeply nested code, since it ensures that the stack is unwound and everything is properly destroyed. I would define an empty type solely to be thrown for this exception, probably nested inside Engine
:
class Engine {
public:
// ...
struct ExitException {};
// ...
};
and throw it from Engine::update
to exit:
void Engine::update(){
SDL_PollEvent(&event);
if(event.type == SDL_QUIT) {
throw ExitException();
}
}
which you can catch in main
to exit cleanly:
int main() {
Engine engine;
engine.init();
try {
while(true) {
engine.update();
engine.render();
}
} catch(Engine::ExitException&) {}
}
Upvotes: 2