std::optional (C++17)
One-Liner
A container that represents "a value may not exist," which is safer and more intuitive than returning a raw pointer or using an output parameter.
Header
#include <optional>
Core API Quick Reference
| Operation | Signature | Description |
|---|---|---|
| Construct | optional() | Default construct, contains no value |
| Assign empty | optional& operator=(nullopt_t) | Sets the state to no value |
| Check for value | explicit operator bool() const | Returns true when a value is present |
| Check for value | bool has_value() const | Same as above |
| Get value | T& operator*() | Dereferences to get the value (undefined behavior if no value is present) |
| Safe get | T& value() | Gets the value, throws bad_optional_access if no value is present |
| Get or default | T value_or(const T& default_value) const | Returns the value if present, otherwise returns the default value |
| In-place construct | T& emplace(Args&&... args) | Constructs the value in-place |
| Reset | void reset() noexcept | Destroys the contained value |
Minimal Example
cpp
#include <iostream>
#include <optional>
#include <string>
std::optional<std::string> find(bool b) {
return b ? std::optional<std::string>{"found"} : std::nullopt;
}
int main() {
auto res = find(false);
std::cout << res.value_or("not found") << '\n';
if (auto val = find(true))
std::cout << *val << '\n';
}Embedded Applicability: High
- A zero-overhead abstraction; when no value is present, it only occupies storage the size of one
bool, with no heap allocation involved - Can replace raw pointers as function return values for operations that might fail, avoiding the risk of null pointer dereferences
- Fully supported since C++17, and member functions are comprehensively
constexprstarting in C++23, further broadening its use cases
Compiler Support
| GCC | Clang | MSVC |
|---|---|---|
| TBA | TBA | TBA |
See Also
Some content referenced from cppreference.com, licensed under CC-BY-SA 4.0