3 ms·
Yes, of course RAII is much shorter than a contrived example designed to be as long as possible. Here's a much shorter version: int unsafe2() {
by KeytarHero 11y ago
Yes, of course RAII is much shorter than a contrived example designed to be as long as possible. Here's a much shorter version:
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?
- WizzleKake 11y agoWhy not just put a and b on the stack then? ;) 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."
- KeytarHero 11y agoBecause it's an example of allocating things on the heap. You could also say the same about the "good" RAII version shown - but then there wouldn't be much point to the article, would there?
- lumpypua 11y agoHow does this version handle exceptions?
- KeytarHero 11y agoIt doesn't. Just like the example it replaces. 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.
- st3fan 11y agoThe original example does actually properly deal with exceptions.
- Devid2014 11y agoThis code work with assertion that constructors of A and B will never throw !
- Devid2014 11y agoDo you want to tell that this is correct and bug free code ? This is a example how to create lot of Memory Leaks.
- KeytarHero 11y agoIt's certainly not bug free. But that's not the point. All I did was rewrite that example with half as much code. The point of that example seems to be "look how much less code RAII takes!" and I'm just trying to show that, although you should use RAII, that's not the reason why.
- deleted 11y ago[deleted]
- fiveoak 11y agoWon't this leak A if B's constructor throws an exception?
- jasode 11y agoI think 3 responses here have misinterpreted what you're illustrating. (e.g. "won't that leak?!?!") 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".
- KeytarHero 11y agoExactly. Thanks.