0

Okay so I am a really new to C++. I do have a java background, but with c++ I know I now have to do my own garbage collection.

Here is my scenario:

int main(){
float * pt;
while(true){
 // some code
}
delete pt;
return 0;

Say you are in a endless while loop and then you decide to end your program by clicking on the close button on the window. What does closing the program do? Does it terminate the while loop, and then execute the delete command? Or does it simply terminate the program without completing the delete command.

Brian Thorpe
  • 317
  • 2
  • 13

3 Answers3

5

A simple C++ program such as this has no concept of "clicking the close button". You don't even deal with that until you start playing with GUI toolkits. The different ways of terminating this program depend entirely on how you are running it. Most likely you are running it in some sort of terminal or command line window. If that terminal provides a close button, then clicking the close button is actually triggering some event in the terminal application. It is entirely up to that application how it deals with your still running program. Often, the terminal will force terminate any child processes. This is however very platform specific. (For Linux, see Signals received by bash when terminal is closed)

If you're worried about the fact that your resource may not be deleted if your program is force terminated, don't. Any modern operating system will clean up the resources allocated by a process when that process is ended.

Community
  • 1
  • 1
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
2

It depends on whether the window is a console window or a normal UI window, and on the operating system. If you close an UI window, the process won't actually terminate, and you'll have a chance to do other things (like cleanup). For console windows, the process will be forcefully terminated, but that's more OS-dependent.

Either way, it doesn't really matter whether a delete command is executed at the end because the process is terminating anyway, and the process's heap will be entirely reclaimed regardless of what was still in it.

user1610015
  • 6,561
  • 2
  • 15
  • 18
0

like sftrabbit said before, you don't have to worry your about delete, when terminating the process. but if you have to do something more complicated, like sending a signoff message to a server, or committing database stuff, there's atexit().

void mycleanup() {
    // do something here.
    // downside is ofc, that you can only use global stuff ;(
}


int main(){

atexit(mycleanup);

while(true){
 // some code
}

return 0;
berak
  • 39,159
  • 9
  • 91
  • 89