Suppose I have a class like this:
#include <iostream>
using namespace std;
class Boda {
private:
char *ptr;
public:
Boda() {
ptr = new char [20];
}
~Boda() {
cout << "calling ~Boda\n";
delete [] ptr;
}
void ouch() {
throw 99;
}
};
void bad() {
Boda b;
b.ouch();
}
int main() {
bad();
}
It seems that destructor ~Boda
never gets called, thus the ptr
resource never get freed.
Here is the output of the program:
terminate called after throwing an instance of 'int'
Aborted
So it seems the answer to my question is No
.
But I thought that the stack got unwound when an exception got thrown? Why didn't Boda b
object get destructed in my example?
Please help me understand this resource problem. I want to write better programs in the future.
Also, is this the so called RAII
?
Thanks, Boda Cydo.