on my OpenGL Program, I want to clean up memories by using c++ 'delete' macro. but, as you know, when OpenGL window is closed, it wouldn't give context to 'main' function, so even though I write code like this:
...
...
glutMainLoop();
//expected to be called after glutMainLoop()
delete[] a,b,c;
...
...
delete macro will not be called. Are there any elegant way to clean up my memories?
First things first in C++ delete
is not a macro, it's an operator. Second you should not use new
and delete
at all, but make use of RAII, i.e. rely on your object's scoping for them to be deallocated. As soon as an object goes out of scope its destructor gets called which allows you to deallocate and finalize.
That being said, cleaning up behind yourself upon process termination is important mostly for debugging purposes; if somewhere in your cleanup routine you leave stuff behind that means you have a bug in the cleanup code.
However from a resource deallocation point of view it's actually a bad idea to explicitly deallocate operating system resources: In a long running process the OS will swap out everything that's not actively used. So if you have some address space allocated (by code, data or something else) but don't use it, the OS will decide to either write it out to swap space or (if the resources have been mapped in from storage) to discard the pages, so that only when it's being accessed its repopulated from storage.
If however your process just terminates, the OS can simply discard all the allocations without second look and more importantly without paging in the memory contents from storage. Where specific reset code must be called, this happens where required.
This is the exact mindset in which the original GLUT was designed: Just terminate the process once you're done using it. Note that in a GLUT-ish program you'll hardly allocate objects in main
. It will happen either through interactive user request in one of the input event handlers, or in the idle functions. These are also the places where to free no longer needed instances.