Daily bit(e) of C++ | accessing std::optional
1 min readJul 5, 2024
Daily bit(e) of C++ ♻️110, Accessing the value stored inside of C++17 std::optional.
The std::optional (C++17) is a container for representing a single optional value.
The class offers several interfaces for accessing and querying the presence of a contained value. The choice depends on your coding style and your desired exception semantics.
#include <optional>
struct Data {
void method() {}
int v;
};
std::optional<Data> x{Data{1}};
// Pointer-style noexcept interface
if (x != std::nullopt) {
x->method();
auto v = x->v;
// decltype(v) == int
// v == 1
}
// Explicit throwing interface
if (x.has_value()) {
auto y = x.value();
// decltype(y) == Data
// y.v == 1
}
std::optional<Data> y;
try {
y.value(); // throws bad_optional_access
} catch (const std::exception& e) {
// e.what() == "bad optional access"
}
// Default-value interface, throws only if construction
// of the contained type throws
auto z = x.value_or(Data{2});
// z.v == 1
x = std::nullopt; // or x.reset();
z = x.value_or(Data{2});
// z.v == 2