3

I am developing c++ command line project in visual studio. I need to capture application closing event (closing application with CTRL+Z or closing command line window while running the application).

My App look like:

  int main()
    {
       //crete app object, will open some files and run the code.
       myApp app;
       app.run();

       getchar();
    }

If I close the application explicitly as I mentioned above, myApp destructor will not be executing. so I need some way to capture this closing event in my application (Like QObject::closeEvent() in Qt).

Thanks in advance.

NDestiny
  • 1,133
  • 1
  • 12
  • 28
  • It seems to throw a `CTRL_CLOSE_EVENT` on windows, [here](http://stackoverflow.com/questions/696117/what-happens-when-you-close-a-c-console-application) is something that may help you. – Jeff Bencteux Dec 09 '14 at 10:35
  • Ctrl+Z just means to end STDIN and close the handle. It's totally application-specific what it does after that. For closing the command window, see the link that @JeffreyBencteux posted. – Ryan Bemrose Dec 12 '14 at 07:38
  • `atexit` function specifies function which is automatically called without arguments when the program terminates normally. – Pie_Jesu Dec 16 '14 at 12:38

1 Answers1

0

In the usual case destructor is not caused for objects created in main(). But there is a good & elegant solution - you can put your code into the extra parentheses, and then the destructor will be invoked:

int main()
{
    {        
        myApp app;
        app.run();

        getchar();
    } // At this point, the object's destructor is invoked
}
Vladimir Bershov
  • 2,701
  • 2
  • 21
  • 51