Zach Starnes
Zach Starnes

Reputation: 3198

Quit program when destructor is run in class

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

Answers (2)

Casey
Casey

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

kmort
kmort

Reputation: 2948

If you want to end your program when the Engine destructor is called, you can use exit();

Take a quick look at this for more information.

Upvotes: 0

Related Questions