4 ms·
the meat of the article: "Another strong link between exceptions and RAII is in constructors. Constructors cannot have return values. Therefore, if a construct
by chillaxtian 11y ago
the meat of the article:
"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.
- sseagull 11y agoThe only pattern I can think of is to construct via a free function. The free function would call the real (basically empty) constructor, and then fill it in via other member functions or by directly accessing the data (via friendship). This free function would be able to allocate memory, etc, and return error flags. 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)
- deleted 11y ago[deleted]
- gpderetta 11y agoYes, a free or static member function that returns an Either-like object is the way to maintain strong RAII invariants while avoiding exceptions. Either, named Result, has been proposed of the next standard. 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.