In college, when learning C++ specifically, we’re always taught that we need to deallocate dynamically allocated memory or close an open file using a deconstructor. What is the difference between that and just using the operating system call exit(0)? Just wondering.
>Solution :
They are not comparable. Apples and oranges
exit() is a C library function. Cpp Reference tells us:
Causes normal program termination to occur.
Several cleanup steps are performed:
- functions passed to atexit are called, in reverse order of registration
- all C streams are flushed and closed
- files created by tmpfile are removed
A deconstructor is a C++ specific feature. It’s a class member function that handles cleanup of an object when it goes out of scope. Cpp Reference tells us:
A destructor is a special member function that is called when the lifetime of an object ends. The purpose of the destructor is to free the resources that the object may have acquired during its lifetime.
You call exit() once and the program ends. Meanwhile destructors are executed all of the time. Because objects get created and go out of scope all the time. Just think of local variables. Or during copying of objects.