Analysis on the code of throwing exceptions in stack-unwinding by destructor

Source: Internet
Author: User

Pursuant to mecpp clause 11. The START section:

In either case, the Destructor is called. The first is to delete an object normally. For example, the object is out of scope or is explicitly deleted. The second is to delete an object from the exception handling system during Stack-unwinding.
In the preceding two cases, exceptions may be activated or not activated when you call the destructor. Unfortunately, there is no way to separate the two situations within the destructor. Therefore, when writing a destructor, you must conservatively assume that an exception is activated. If the Destructor throws an exception while an exception is activated, and the control of the program is transferred outside the destructor, C ++ calls the terminate function. This function is used as its name indicates: It terminates the running of your program and terminates immediately, even if some objects are not released.

It is almost confusing, so I wrote the following code to help understand:

# Include <iostream>
# Include <exception>
Using namespace STD;

Class class_test {
Public:
Class_test (void ){}
~ Class_test (void)
{
// Throw bad_alloc ();
// If an exception is thrown here, terminate () is called ()
Cout <"~ Class_test ()... "<Endl;
Cin. Get ();
}
PRIVATE:
};
Void funtest0 (void)
{
Class_test OBJ;
Cout <"f0...." <Endl;
Throw bad_alloc ();
Cout <"funtest0 () ......" <Endl;
}
Void funtest1 (void)
{
Class_test OBJ;
Cout <"F1...." <Endl;
Funtest0 ();
Cout <"funtest1 () ......" <Endl;
}

Int main ()
Try
{
Class_test OBJ;
Funtest1 ();
Cin. Get ();
Return 0;
}
Catch (bad_alloc & E)
{
Cout <E. What () <Endl;
Cin. Get ();

}

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.