Original Post
When an exception thrown, all the objects successfully constructed in the try block will be destroyed. But consider the following code: The output is: object ID:0 generated. object ID:1 generated. object ID:2 generated. object ID:3 generated. object ID:2 destroyed. exception caught The first element in the a3 array is successfully destroyed but a1 and a2 not. Why? If I change the try block to the following code: The output is: object ID:0 generated. object ID:1 generated. object ID:2 generated. object ID:3 generated. object ID:2 destroyed. object ID:1 destroyed. object ID:0 destroyed. exception caught a1 and a2 are successfully destroyed. I am a little bit confused.
#include <iostream>
using namespace std;
class A {
public:
A() throw(int) {
ID = count++;
cout << "object ID:" << ID << " generated." << endl;
if (3 == ID)
throw 0;
}
~A() {
cout << "object ID:" << ID << " destroyed." << endl;
}
private:
static int count;
int ID;
};
int A::count = 0;
int main()
{
try {
A *a1 = new A;
A *a2 = new A;
A *a3 = new A[3];
delete a1;
delete a2;
delete[] a3;
cout << "Exit Now" << endl;
} catch(int) {
cout << "exception caught" << endl;
}
}
try {
A a1;
A a2;
A *a3 = new A[3];
delete[] a3;
cout << "Exit Now" << endl;
}