Exploring the power of std::optional in C++

CMP
3 min readJan 11, 2024

As the C++ language has evolved over the years, new features and functionality have been added to make programming more efficient and expressive.

What is std::optional?

In C++17, std::optional and the <optional> header were added, allowing programmers to cleanly handle optional values without needing to use some type of programmer-defined special value.

One clear use case for std::optional is for a return value that may fail. Consider the following example:

#include <iostream>
#include <optional>
#include <vector>

std::optional<int> findItem(const std::vector<int>& items, int target) {
for (const auto& item : items) {
if (item == target) {
return elem;
}
}

return std::nullopt;
}

int main() {
std::vector<int> items = {1, 2, 3, 4, 5};
int target = 3;

auto result = findItem(items, target);

if (result.has_value()) {
std::cout << "Item found: " << result.value() << std::endl;
} else {
std::cout << "Item not found." << std::endl;
}

return 0;
}

Here, the findItem function has a return type of std::optional<int> rather than simply int. This clearly conveys the fact that findItem may not find the target value.

Furthermore, there is no need to construct some sort of optional object — simply return the int, or return std::nullopt if there is no item to return. Then from the caller side, check if the function returned a value by calling the .has_value() method and retrieve…

--

--

CMP

Software engineer specializing in operating systems, navigating the intracicies of the C++ language and systems programming.