Item 8: Destructors do not throw exceptions effective C + + notes

Source: Internet
Author: User

Item 8:prevent exceptions from leaving destructors.

Destructors do not throw exceptions

Because destructors are often invoked on their own initiative, exceptions thrown in destructors are often difficult to capture, triggering an abnormal exit or undefined behavior. For example, when an object array is being refactored. Throws more than one exception, but an exception that exists at the same time is forbidden in the C + + standard , so the program exits abnormally:

class Widgets { Public:  ~Widgets() { ... }            //Assume this might emit an exception};void dosomething(){  STD::Vector<Widgets> v;}                              //V is automatically destroyed here

In fact, an object in a container that throws an exception while it is being destroyed can also cause a possible object to be refactored. Cause a resource leak. The resources here can be either memory or database connections. or other types of computer resources.

The destructor is called by C + + and does not include a call to it, so the exception it throws cannot be caught. For objects in a stack, it is refactored when it leaves the scope. For objects in the heap. At the time it is destroyed delte .

Please see:

class C{ Public:    ~C(){ Throw 1;}};void Main(){    Try{        C C;    }    Catch(int e){}}

The exception to the destructor is not captured. Because try{} code block only has one line of code c C . It does not throw an exception. When compiled by homebrew gcc 5.1.0, this error output is generated when executed:

libc++abi.dylib:terminating with uncaught exception of type int  

Perhaps you think in try with delete manually frees the heap object to catch the exception. Let's try it out:

c  *  p  =  new  c   try  { delete  p   }  catch   ( int  e  ) {}  

The code above will give the same error output:

libC++abi.dylib: terminating with uncaught exception of type int

This simply means that delete it is not a direct call to the destructor, it is just a keyword.

Destructors are also called by C + +. In fact. Assuming the above is not delete the case, the program does not produce an error, which is a p memory leak. The memory is reclaimed by the operating system after the program exits.

Then in the destructor. The possible exceptions should be disposed of. Guarantees that the object can be completely freed . Since unsafe code always appears in destructors, we can only swallow exceptions or exit programs . Such

class Dbconn{ Public:    ~Dbconn{        if(!closed){            Try{                DB.Close();            }            Catch(...) {              Cerr<<"Database shutdown failed"<<Endl;              //or exit the program directly                //Std::abort ();            }        }    }Private:    DBConnection DB;};

In addition, the above catch (...) In the ... is not an ellipsis, it is a legal identifier that represents an indeterminate form of participation.

But for a good design, we need to let the customer know that something is wrong here.

Just provide a new function for the unsafe statement. In the destructor we still run the default action (ignoring, logging, or ending the program).

class  dbconn  { public  :  void  span class= "n" >close  () { db   close   ();  }   ...  

This general approach gives the customer the opportunity to shut down the database and handle the exception themselves. Of course, assuming he gives up the opportunity, he can't blame us for letting the program quit or swallow the anomaly.

Unless noted. This blog article is original, reproduced please link to the form of this article address: http://harttle.com/2015/07/26/effective-cpp-8.html

Item 8: Destructors do not throw exceptions effective C + + notes

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.