How to Use std::optional in C++: Syntax and Examples
Use
std::optional<T> to represent a value that may or may not be present in C++. You can check if it contains a value with has_value() or by converting it to bool, and access the value with value() or * operator.Syntax
std::optional<T> is a template that holds either a value of type T or no value. You can create an empty optional or initialize it with a value. Use has_value() or operator bool() to check if it contains a value. Access the value with value() or *.
cpp
std::optional<T> opt; // empty optional std::optional<T> opt2 = value; // optional with a value if (opt.has_value()) { T val = opt.value(); // get the value safely } if (opt) { T val = *opt; // get the value using operator* }
Example
This example shows how to create an optional, check if it has a value, and access the value safely.
cpp
#include <iostream> #include <optional> int main() { std::optional<int> maybeNumber; // empty optional if (!maybeNumber) { std::cout << "No value yet\n"; } maybeNumber = 42; // assign a value if (maybeNumber.has_value()) { std::cout << "Value is: " << maybeNumber.value() << "\n"; } // Using operator* std::cout << "Value using *: " << *maybeNumber << "\n"; return 0; }
Output
No value yet
Value is: 42
Value using *: 42
Common Pitfalls
- Accessing the value without checking if it exists causes
std::bad_optional_accessexception. - Do not assume an optional always has a value; always check with
has_value()oroperator bool(). - Assigning
std::nulloptclears the optional.
cpp
std::optional<int> opt; // Wrong: accessing value without checking // int val = opt.value(); // throws exception // Right way: if (opt) { int val = opt.value(); } else { // handle no value case }
Quick Reference
| Operation | Description | Example |
|---|---|---|
| Create empty optional | Optional with no value | std::optional |
| Create with value | Optional initialized with a value | std::optional |
| Check if has value | Returns true if value exists | if (opt.has_value()) or if (opt) |
| Access value | Get the stored value | opt.value() or *opt |
| Reset optional | Clear the value | opt = std::nullopt; |
Key Takeaways
Use std::optional to safely represent values that may be missing.
Always check if an optional has a value before accessing it.
Access the value with value() or operator* after confirming presence.
Assign std::nullopt to clear an optional's value.
std::optional helps avoid unsafe null pointers and exceptions.