Search⌘ K

A Basic Example Of std::optional

Explore how std optional in C++17 helps manage nullable values by safely containing optional data, checking for presence, and accessing stored values efficiently to improve code safety.

We'll cover the following...

Here’s a simple example of what you can do with optional:

C++
// UI Class...
std::optional<std::string> UI::FindUserNick()
{
if (IsNickAvailable())
return mStrNickName; // return a string
return std::nullopt; // same as return { };
}
// use:
std::optional<std::string> UserNick = UI->FindUserNick();
if (UserNick)
Show(*UserNick);

In the above code, we define a function that returns an ...