Reputation: 1670
We are porting our codebase from Objective-C to C++ 11. In Obj-C, most every object inherits from NSObject and then you only pass pointers around. This is very convenient for errors, as you can usually let the caller know there is no object by simply returning nil (null). While porting to C++, I've begun to run into the fact that there is no real parallel (or at least it would be ugly to do it that way with memory management). Do libraries usually simply throw an exception up to the caller even for non-critical errors? how do you know what layer is proper to catch it on? Is it more kosher to pass an error variable by reference?
Upvotes: 0
Views: 231
Reputation: 377
std::optional
is a nice way to do this (as pointed out by user202729 in his comment).
If you don't have C++17 support you can use boost::optional
which is pretty much the same as C++17's std::optional.
If you also want to return informational data in case of error (e. g. an error string) you should take a look at "expected". It neither made it into STL yet nor into boost but there is a proposal for STL already: https://github.com/viboes/std-make/blob/master/doc/proposal/expected/DXXXXR0_expected.pdf and there are some independent implementations available, e. g.: https://github.com/martinmoene/expected-lite
Upvotes: 1