Sometimes, we are required to dynamically allocate memory and construct a class in that memory. That's where the troubles start. Take a look at the following code:
bool foo1() { foo_class* p = new foo_class("Some data"); const bool something_else_happened = some_function1(*p); if (something_else_happened) { delete p; return false; } some_function2(p); delete p; return true; }
This code looks correct at first glance. But, what if some_function1()
or some_function2()
throws an exception? In that case, p
won't be deleted. Let's fix it in the following way:
bool foo2() { foo_class* p = new foo_class("Some data"); try { const bool something_else_happened = some_function1(*p); if (something_else_happened) { delete p; return false; } some_function2(p); } catch (...) { delete p; throw; ...