C + + discussion on whether constructors and destructors can throw exceptions

Source: Internet
Author: User

Constructors and destructors respectively manage the creation and release of objects, and are responsible for the birth and death of objects. When an object is born, the constructor is responsible for creating and initializing the object's internal environment, including allocating memory, creating internal objects, opening related external resources , and so on. When the object dies, the destructor is responsible for closing the resource, freeing the internal object, and the allocated memory .

Where the object is at stake, if there is a problem with the program code, a memory leak can often occur, creating a ghost that might compromise the system's Operation . A large number of facts show that the business logic code is very rigorous program in the operation still found that there is a memory leak, most of the construction and destruction of the code in the part of the problem .

Many programmers are accustomed to object-oriented programming, creating an object when needed and releasing it when not in use. This habit simplifies our thinking and is the benefit of object-oriented programming ideas. Perhaps because too accustomed to, many programmers have neglected in the moment of life and death of the object may also produce abnormal problems, this phenomenon is worth our serious reflection.

In fact, the object of life and death of the anomaly is a controversial issue. Even different programming languages have different attitudes towards the anomaly of the object and death.

The C + + language says: An object is an abnormal problem in the process of being born, and that object is an inanimate freak. Since it is not a complete object, there is no notion of destruction or release at all. Therefore, when C + + generates an exception during the execution of a constructor, it does not invoke the object's destructor, but simply cleans and releases the variable space of C + + management before the exception, and then throws the exception to the programmer.

So what about the exceptions in the destructor ?

Object in the course of the death of the exception and raises an interesting question, "want to Die" or "dead half can not die"! So, is this object dead or alive? This dead and alive object is as interesting as the "Schrödinger's cat" in Quantum theory. It does exist, but it is hard to ponder!

For this reason,C + + does not dwell on this complex problem at all, but instead takes the simplest approach: if the destructor throws an exception, it will directly cause the current execution thread to terminate abnormally! If there is a destructor in the main thread, the program exits immediately!

The C + + approach is understandable when the code has entered a dead end that cannot be figured out, and the object can only go insane, destroying the entire program world! It seems that not all mortal beings can not escape the abyss of suffering, in fact, the process of running procedures also have the heart knot not open!

So, " never throw exceptions in destructors " becomes an iron law for writing C + + code!



Exceptions in constructors and destructors

1. Constructors can throw exceptions.

2. The C + + standard Specifies that destructors cannot, and should not, throw exceptions.

More effective C + + on the 2nd two reasons:

1) If the destructor throws an exception, the program after the exception point does not execute, and if the destructor performs some necessary actions after the exception point, such as releasing some resources, these actions do not execute and cause problems such as resource leaks.

2) Normally, when an exception occurs, the mechanism of C + + calls the destructor of the constructed object to release the resource, and if the destructor itself throws an exception, the previous exception has not been processed and a new exception has been created, causing the program to crash.

Workaround:

1) never throw an exception in a destructor.

2) Usually the 1th is sometimes not guaranteed. You can take the following methods:

 
~classname () {  try{      do_something ();  }  catch () {  //You can do nothing here, just make sure the catch block's program throws an exception that is not thrown out of the destructor.   }}



Summary

Destructors are not called after a constructor throws an exception

General summary of throwing exceptions in destructors
(1) the implementation of destructors in C + + should not throw exceptions;
(2) If the destructor throws an exception, then your system will become very dangerous, perhaps a long time what error will not be produced, but perhaps your system will sometimes inexplicably collapse and quit, and no signs of it, it is difficult to break the ground you find the problem of what is present in the place;
(3) when there are some possible anomalies in a destructor, it is necessary to encapsulate the possible exception in the destructor, and never let it throw out the function;
(4) must bear in mind these several summary, the destructor throws the exception causes the program unknown reason the collapse is the fatal internal injury of many systems!

C + + discussion on whether constructors and destructors can throw exceptions

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.