Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it important to call destructors at program termination?

Tags:

c++

If you check this link http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=107 it's written:

"For example, the abort() and exit() library functions are never to be used in an object-oriented environment—even during debugging—because they don't invoke objects' destructors before program termination."

Why does the destructor need to be called when one calls exit? (Since the OS guarantees memory will be reclaim whenever a program exits, right?)

like image 385
brett Avatar asked Jan 21 '23 11:01

brett


1 Answers

Destructors can, and often do, other operations besides freeing memory and/or resources. They are often used to make certain other guarantees such as user data is written to a file or non-process specific resources are in a known state. The OS won't do these types of operations on exit.

That being said, any program which relies on these types of actions is fundamentally flawed. Use of exit and abort are not the only ways destructors are avoided. There are many other ways a destructor can be circumvented. For example user forcable terminating the process or a power outage.

I definitely disagree with the use of never in the quoted passage. I can think of at least one situation where you absolutely don't want destructors executing: corrupted memory. At the point you detect corrupted memory you can no longer make any guarantees about the code in your process, destructors included. Code which should write data to a file might delete / corrupt it instead.

The only safe thing to do when memory corruption is detected is to exit the process as fast as possible.

like image 108
JaredPar Avatar answered Mar 02 '23 15:03

JaredPar