I was debating with some colleagues about what happens when you throw an exception in a dynamically allocated class. I know that malloc
gets called, and then the constructor of the class. The constructor never returns, so what happens to the malloc
?
Consider the following example:
class B
{
public:
B()
{
cout << "B::B()" << endl;
throw "B::exception";
}
~B()
{
cout << "B::~B()" << endl;
}
};
void main()
{
B *o = 0;
try
{
o = new B;
}
catch(const char *)
{
cout << "ouch!" << endl;
}
}
What happens to the malloced memory o
, does it leak? Does the CRT catch the exception of the constructor and deallocate the memory?
Cheers!
Rich