Search code examples
c++option-typenullptr

convert nullptr to std::optional


I have a library defining method() that returns type V* and can return nullptr. What's the best way to wrap that method to turn the value into a std::optional<V>?

The naive way would be something like:

std::optional<V> maybe_value;
V* value = method();
if (value != nullptr) {
    maybe_value = *value;    // assuming the type is even copyable
}

But I was hoping there'd already be some STL function I could use to do this as a one-liner wrapper around method().


Solution

  • Your way looks basically fine to me, and is roughly what I'd do. You don't want a one-liner here as it would not be very clear. Ultimately you can create a function for it if you like.

    One concern: be very careful with ownership semantics here. Who owns *value? Can it be copied? Is that meaningful? Can you move it instead? Who frees the original object?

    Always ask these questions when passed a pointer, even if it appeared that the pointer was only chosen in order to add nullability.

    To be quite honest, although std::optional is preferable in new code (or code you're refactoring), I'm not convinced that wrapping a function like this is worth the potential confusion, not to mention the cost of a copy (if, indeed, that is necessary).