Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between a deconstructor and exit() C++

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading