When should I use std::optional
in C++?
In what situations is it appropriate to use std::optional
instead of just regular values or pointers?
You should consider using std::optional
in C++ when you have a value that may or may not be present, such as:
Function return values
If a function might not always return a meaningful value, std::optional
is a good way to represent that. For example:
#include <optional>
#include <string>
std::optional<std::string> GetMiddleName(
const std::string& fullName) {
// Parse full name
// if middle name found, return it
// else return empty optional
return std::nullopt;
}
Class members
If a class has a field that is not always applicable or known at construction time, std::optional
is a safe way to model that:
#include <optional>
#include <string>
class Character {
std::string name;
// age may not be known
std::optional<int> age;
};
Optional function arguments
While default arguments are often used for this, std::optional
can make it more explicit:
#include <optional>
void SetVolume(std::optional<double> volume) {
if (volume) {
// set volume to *volume
} else {
// set to default volume
}
}
In general, std::optional
is useful when you need to distinguish between a value not being present vs the value being present but potentially 0, empty string, null pointer etc. It makes your code's intent clearer.
Nullable Values, std::optional
and Monadic Operations
A comprehensive guide to using std::optional
to represent values that may or may not be present.