C++: RAII without exceptions
eli.thegreenplace.net
eli.thegreenplace.net
But I'm wracking my brain trying to think why anyone would think that exceptions are needed for RAII and am unable to come up with anything.
(I'd have thought the cleanup-in-the-destructor part was more important, and thus more worthy of being emphasised in the acronym - but there you go.)
guard x();
if (!x) {
// an error occurred
return x.error_code();
}
x->do_stuff();
You don't have exceptions so of course you're now required to check for errors explicitly.I like RAII, but I haven't used it significantly. Meanwhile, I'm not a fan of exceptions. So, how people make the two work together smoothly is an interesting topic for me...
Without exceptions though your RAII objects can be invalid and, frankly, should be called something like RAIIUEH (Resource Allocation Is Initialization Unless Error Happened).
How does your team smooth out handling errors in RAII without exceptions?
But then reading the comments section, I get that the author completely missed the point.
The claimers, whoever they are, aren't claiming RAII needs exception for deallocation, which the author has covered.
But they claim RAII needs exception to handle resource allocation failures. Which the author is trying to undermine saying that is a rare case. Which probably isn't that rare.
"Another strong link between exceptions and RAII is in constructors. Constructors cannot have return values. Therefore, if a constructor encounters an error condition, you either throw an exception or mark some internal error state. The latter has its issues (which is why alternative methods of construction are recommended in code without exceptions), so throwing an exception is the most common approach."
wish the author had provided examples of the alternative methods of construction, rather than explain RAII from scratch.
You could even make the real constructor private, which would prevent inadvertently creating an object with an invalid state.
(Could also be done with a static member function, I suppose)
Unfortunately C++ still doesn't have good facilities for dealing with monads (i.e. do notation) making working with Either (and futures, and optionals) quite awkward.