Why is it important to call destructors at program termination?

If you check this link http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=107 he wrote:

"For example, the library functions abort () and exit () should never be used in an object-oriented environment - even during debugging - because they do not call object destructors before the program terminates."

Why does the destructor need to be called when you call exit? (Since the OS ensures that memory will be restored whenever the program exits, right?)

+4
source share
2 answers

Destructors can and often perform other operations than freeing up memory and / or resources. They are often used to ensure that some other guarantees, such as user data, are written to a file or non-process related resources are in a known state. The OS will not perform these operations upon exit.

Thus, any program that relies on these types of actions is fundamentally wrong. Using exit and interrupt is not the only way to avoid destructors. There are many other ways a destructor can get around. For example, the user can turn off the process or turn off the power.

I definitely disagree with what is never quoted in the quote. I can imagine at least one situation where you absolutely do not want destructors to execute: corrupted memory. The moment you discover corrupted memory, you can no longer make any guarantees regarding the code in your process, including destructors. Code that should write data to a file can delete / ruin it.

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

+9
source

First, I would like to advise that "do not trust anyone that you read." Probably, since JaredPar said that the destructor can make some entries and close the resources of the OS resource. In the event that you cause an interrupt or exit from this, it will never happen.

But I certainly do not agree with the quote. Abort is the best and fastest way to find programming errors in the development cycle. As a developer, you certainly donโ€™t blindly put everywhere in the code, but on the condition that you know that this should never have happened. You stop working when you know that another programmer or you messed up somewhere in the code, and it is better to stop than to handle the error. I experienced a situation where cancellation really saved my @ $$.

0
source

All Articles