So are there any reasons to prefere one over the other?
They express very different intent: optional
says that the function may not give a result to give you (and that is not an error case). unique_ptr
tells you something about ownership semantics (and is more acceptable to use with null, to express an error).
Usually I would use the one that expresses best the intent behind the interface.
For example, consider that you were writing a HTTP server, that attempts to parse a received buffer into a HTTP request object. When you attempt to parse an incomplete buffer, there is no error case, you simply have to wait and buffer more data, then try again.
I would express this using optional
,to make it clear that the function may not return anything (and not returning anything is not an error case).
In case my parsing had to validate stuff (e.g. a regex parser should yield an error if the parsed expression is invalid regex) I would return a null unique_ptr
, or better yet, throw an exception.
unique_ptr
is very inappropriate for a find operation, a raw pointer is exactly what you need, and a bool flag is completely unnecessary! – Marxistboost::optional
. – Soursop