There are several ways to check if a std::optional
contains a value:
has_value()
This is an explicit way to check. It returns true
if the optional contains a value, and false
if it is empty.
#include <iostream>
#include <optional>
int main() {
std::optional<int> maybe_int = 10;
if (maybe_int.has_value()) {
std::cout << "has value" << std::endl;
} else {
std::cout << "no value" << std::endl;
}
}
has value
operator bool()
std::optional
has a conversion operator to bool
, so it can be used directly in boolean contexts like if
statements. It returns true
if the optional contains a value, and false
if it is empty.
#include <optional>
#include <iostream>
std::optional<int> maybe_int = 10;
if (maybe_int) {
std::cout << "has value" << std::endl;
} else {
std::cout << "no value" << std::endl;
}
has value
std::nullopt
You can directly compare an optional to std::nullopt
to check if it is empty.
#include <iostream>
#include <optional>
int main() {
std::optional<int> maybe_int = 10;
if (maybe_int != std::nullopt) {
std::cout << "has value" << std::endl;
} else {
std::cout << "no value" << std::endl;
}
}
has value
In general, using has_value()
is the most explicit and self-explanatory way. Using the bool
conversion operator or comparing to std::nullopt
can lead to more concise code, but it might be less obvious what the intent is.
Remember, trying to access the value of an empty optional leads to undefined behavior (if using operator*
or operator->
) or an exception (if using value()
). Always check that the optional has a value before trying to access it.
Answers to questions are automatically generated and may not have been reviewed.
std::optional
A comprehensive guide to using std::optional
to represent values that may or may not be present.