C++ and Beyond 2012: Andrei Alexandrescu - Systematic Error Handling in C++
Why Stack Overflow recommends it
Stack Overflow users link it when answering questions about Rust-style Result types and exception-free C++, since it is the main reference for the Expected<T> pattern.
Recommended by 2 people across 2 different months, 2014 to 2019.
What it is
A conference talk from C++ and Beyond 2012 in which Andrei Alexandrescu presents a systematic approach to error handling in C++. He introduces the Expected<T> type as an alternative to exceptions and error codes, walking through its implementation. This upload is a re-post of the Channel 9 recording.
What people said
Strong rec Nir Friedman · 2015-08 · Stack Overflow · on “C++ equivalent of Rust's Result<T, E> type?”
What you are looking for is exactly Alexandrescu's Expected. I recommend listening to his talk for an in depth understanding: [this video] . He actually goes through the implementation line by line, and you can easily write it yourself and use it well after that. Variant is a more general tool, it can be coerced to do what you want but you're better off with expected. Please see [LINK]
Recommends Jorge Bellon · 2019-02 · Stack Overflow · on “How can I check the failure in constructor() without using exceptions?”
I also came across this problem. I think an elegant solution is making the real constructor private, and then use a factory to return an instance and the error. I'm not keen on retrieving an error via output argument, so I'd put both success and possible instance in a struct: template < class T > struct expect { expect( T v ) : failure(false), value(v) // or std::move(v) { } expect( int e ) : failure(true), error(e) { } bool failure; union { T value; int error; }; }; class A { public: expect<A> create( /* arguments */ ) { if( /* check fails */ ) { return expect(error_code); } return expect( A(/*arguments*/) ); } private: A( /* constructor that does not fail */ ); }; This is a popular pattern
Cites o11c · 2014-10 · Stack Overflow · on “Writing C++ without exceptions?”
It's not hard. In fact I argue that the Result<T> style (also known as expected in Andrei's talk [this video] , but I was inspired by Rust's version [LINK] , particularly the try! macro [LINK] , except that I don't template my Err variant (for functions that fail, all errors are the same)) is a lot easier than using exceptions. The one thing you really have to give up is constructors that do something that can possibly fail. Instead, use the named constructor idiom and only use pretty-much-aggregate constructors after you've already done. As far as bad_alloc , just let it kill the process by unwinding.