Cannot SDL_GL_DeleteContext in destructor

477 Views Asked by At

I am creating an SDL-OpenGL application in D. I am using the Derelict SDL binding to accomplish this.

When I am finished running my application, I want to unload SDL. To do this I run the following function:

public ~this() {
    SDL_GL_DeleteContext(renderContext);
    SDL_DestroyWindow(window);
}

For some reason however, that'll give me a vague segmentation fault (no traces in GDB) and return -11. Can I not destroy SDL in a destructor, do I even have to destroy SDL after use?

My constructor:

window = SDL_CreateWindow("TEST", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1280, 720, SDL_WINDOW_OPENGL | SDL_WINDOW_FULLSCREEN_DESKTOP);
if(window == null) {
    string error = to!string(SDL_GetError());
    throw new Exception(error);
}

renderContext = SDL_GL_CreateContext(window);
if(renderContext == null) {
    string error = to!string(SDL_GetError());
    throw new Exception(error);
}
1

There are 1 best solutions below

0
On

Class destructors may run in a different thread than the thread where the class was created. The crash may occur because OpenGL or SDL may not handle cleanup from a different thread properly.

Destructors for heap-allocated (GC-managed) objects are not a good way to perform cleanup, because their invocation is not guaranteed. Instead, move the code to a cleanup function, or use a deterministic way to finalize the object (reference counting, or manual memory management).