Should I use exit in C ++?

According to C ++ link

exit terminates the process normally by performing regular cleanups to exit programs.

A normal program termination performs the following (in the same order): Objects associated with the current thread with the thread storage duration are destroyed (only C ++ 11). Objects with static storage (C ++), and functions registered with atexit are called. All C-streams (opened with functions in) are closed (and reset if buffered), and all files created with tmpfile are deleted. The control returns to the host environment.

Note that objects with automatic storage are not destroyed when calling exit (C ++).

as far as I know, when the process ends, all the storage used by the process is restored, so that the influence of objects with automatic storage is not destroyed?

+5
source share
3 answers

The problem is that not everything that you can somehow take on is listed in the standard as purification.

For example, many programs and libraries do things such as creating lock files, starting background processes, changing system settings, etc. They can be cleaned up by the OS if you call exit , but they are optional. Failure to comply with these functions can have consequences, from the inability to restart the program (typical for lock files) to a complete system crash (less likely, but possible in some cases).

True, on the topic of a joke. I used to use OIS , the input library for my project. Every time I killed my program in the debugger, key repetition was broken throughout the system, because OIS temporarily disabled it in Linux. I fixed this by changing the settings (and later completely resetting OIS), but this illustrates very well the problems you might encounter when calling exit before you clean your environment yourself.

+5
source

If these destructors are not called, their side effects do not occur: releasing resources in other processes, deleting temporary files outside this folder, clearing non-stream files, etc. etc. etc.

+8
source

In C ++, you should use std::terminate , not exit or abort , to execute the ordered fatal error output, because the code you use may have installed a completion handler to perform critical cleanup.

The default handler std::terminate calls abort .

The stack does not unwind.

Re

" that does not remove the impact of objects with automatic storage?

Since destructors are not called, the cleanup that they can perform is not performed. For example, on Windows, a console window may become unusable if it has a custom text buffer. Temporary files can be left on disk. Assistant processes may not be closed. And so on.

This should be weighed against the possibility of unpleasant things if an attempt at general cleaning is undertaken, for example. because the statement quit, showing that some fundamental assumption about the state of the process is not fulfilled.

+2
source

Source: https://habr.com/ru/post/1247904/


All Articles