CKTIS / C++
std::optional — a value that may be absent
std::optional<T> represents either an object of type T or no value. It separates a missing result from valid values such as 0. Check that a value is present before using the * and -> operators.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <optional>
std::optional<T> item;
std::optional<T> empty = std::nullopt;
if (item) { /* *item; item->member; */ }std::optional<T>, declared in <optional>, stores a value of type T within its own object or contains no value. It is useful when a function may have no result but you do not need an error description. Default construction with std::optional<T> item; produces an empty state; construction from a value of type T produces a state containing a value.
std::nullopt is the constant indicating no value, and std::nullopt_t is its distinct tag type, not the type of the stored result. Use return std::nullopt; to return an empty result, or item = std::nullopt; to remove the stored value.
std::optional::operator bool is an explicit conversion that tests presence; it works in if (item), similarly to item.has_value(). It does not test the stored value itself: an object containing 0 or false still yields true.
std::optional::operator* provides the stored value by reference, while std::optional::operator-> enables access to its members. Both require a value to be present. In C++23, using either on an empty object has undefined behavior; do not expect an exception. The value() member checks this state and throws std::bad_optional_access when no value is present.
This entry targets C++23: the repository compiler flag, with production runtime not attested. The linked working draft is updated and also includes later extensions; its entire contents must not be treated as C++23.
Examples
#include <iostream>
#include <optional>
struct Item {
int count;
};
std::optional<Item> find_item(bool available) {
if (available) {
return Item{0};
}
return std::nullopt;
}
int main() {
const auto item = find_item(true);
if (item) {
std::cout << item->count << ' ' << (*item).count << '\n';
}
const auto missing = find_item(false);
std::cout << std::boolalpha << missing.has_value() << '\n';
}
Result
0 0 false
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.