by KeytarHero · 11y ago · 0 comments
int unsafe2()
{
A* a = new A;
int retval = 0;
if (a->f())
{
B* b = new B;
if (b->f())
retval = b->g();
else
retval = a->g();
delete b;
}
delete a;
return retval;
}
I agree that RAII is a good thing, but can we please avoid straw-man examples?Bjarne says, "Code that creates an object using new and then deletes it at the end of the same scope is ugly, error-prone, and inefficient."
I'm not saying this is the best way to write this code - there are several reasons RAII is better. But in this case, "look how messy non-RAII code is!" isn't the reason.
KeytarHero could have wrote: "Here's a much shorter more realistic version of new/delete code that will have problems such as leakage after exceptions"
Since he didn't make that explicit, 3 replies seem to have misinterpreted the post as: "Here's a much shorter version that won't leak and doesn't need RAII"
Basically, his example is supposed to be "wrong" but it's a shorter version of "wrong".