std::nullopt
std::nullopt is a constant used to represent an empty or uninitialized state for std::optional. It explicitly signals that an optional contains no value.
Key Properties
- Defined in the
<optional>header. - Used to initialize or assign an
std::optionalto an empty state. - Type:
std::nullopt_t, which is a distinct type specifically for this purpose. - Can be used in comparisons to check if an
std::optionalis empty. - Helps improve code readability by clearly indicating the absence of a value.
Example
#include <optional>
#include <iostream>
std::optional<int> findValue(bool found) {
if (found)
return 42;
else
return std::nullopt; // explicitly empty
}
int main() {
auto value = findValue(false);
if (value == std::nullopt)
std::cout << "No value found\n";
else
std::cout << "Value: " << *value << "\n";
}