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 ();
}