Whats the right approach to return error codes in C++

You can return a std::pair holding both an error code (or error object) and the desired return object. The object of interest needs a default constructor or value so you can return something even when an error is encountered.


You can pass variable as reference and return error code in it.


You probably want something like Alexandresu's Expected<T> idiom.


Make a template called, say, Maybe that it parametrized by your return value type. Whenever you return a value, wrap it in this template like this:

Maybe<long> result = object.somemethod();

The Maybe template would have a way of being instantiated with an error code (probably a static method):

return Maybe<long>::error(code);

But ordinarily would just be returned with the value:

Maybe<long> retval;
retval = 15;
return retval;

(You would have to, of course, override the appropriate constructors, assignment operators, etc.)

In the client side you call a method to check for the error.

Maybe<long> result = object.somemethod();
if (result.is_error) 
{ 
    ... handle the error ...
}
else
{
    ... use the result ...
}

Again you'd need the appropriate operators defined to use Maybe<long> wherever there's a long required.

This sounds like a lot of work, but really the work is done once in making a good, bulletproof Maybe template. You'll also have to do some performance tuning on it to avoid nasty overheads. If you want to make it more flexible you can parametrize it on both the return value type and the error type. (This is only a minor increase in complexity.)

Tags:

C++