You should consider using std::optional
in C++ when you have a value that may or may not be present, such as:
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;
}
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;
};
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.
Answers to questions are automatically generated and may not have been reviewed.
std::optional
A comprehensive guide to using std::optional
to represent values that may or may not be present.