Search⌘ K
AI Features

Returning std::optional

Explore how to return std::optional from functions in C++17 to handle nullable values safely. Understand the use of std::nullopt for unavailable values, copy elision benefits, and pitfalls of returning optionals inside braces.

We'll cover the following...

If you return an optional from a function, then it’s very convenient to return just std::nullopt or the computed value.

C++
std::optional<std::string> TryParse(Input input) {
if (input.valid())
return input.asString();
return std::nullopt;
}
// use:
auto oStr = TryParse(Input{...});

In the above example you can see that the function returns std::string computed ...