Effective C + + clause 8

Source: Internet
Author: User

Don't let exceptions escape destructors

Why don't you let the exception escape the destructor, and what are the problems that the exception will cause? It is clear that anomalies can lead to ambiguous behavior.
The following code:
Destructors are called when the container is destroyed, and if the destructor throws an exception, the remaining elements in the container should be destroyed or there may be a memory leak. At this point, if you continue to destroy other elements, there will be an exception, there are two exceptions. The presence of two exceptions can lead to ambiguous behavior. You will also encounter similar problems with other containers of the standard library or any container or array of TR1. What we need to do at this point is to terminate the program in general, to prevent the program from appearing ambiguous behavior

class Widget{public:……~Widget(){……}};void doSomething(){    std::vector<Widget> v;    ……    //v要析构,会调用Widget的析构函数}

In the destructor, sometimes it is unavoidable to throw an exception, as in the case of the book:
What should we do when a database shutdown fails?

classDBConnection{public:……void close();//关闭数据库};classDBConnection{public:……    ~DBConn()//析构函数关闭连接    {        db.close();    }private:        DBConnectiondb;};

There are two ways to avoid this problem:
1. If close throws an exception, terminate the program. This is usually done by calling abort.
2. It's a bad way to swallow this anomaly.

~DBConn()//析构函数关闭连接    {        try{            db.close();        }        catch(……)        {            //记录下对close调用的失败            std::abort();//退出        }    }~DBConn()//析构函数关闭连接    {        try{            db.close();        }        catch(……)        {            //记录下对close调用的失败        }    }

Effective C + + clause 8

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.