Why is this an issue?
The class std::optional
stores an optional value: a std::optional<T>
can either contain a value of type
T
or be empty. One way to access the value of a non-empty optional is the operator*
, making an optional look like a
pointer.
However, the similarity ends there. In particular, the preferred way to assign a value to an optional is to assign it directly (as opposed to
assigning it to the dereferenced value or to the result of the function value()
). In that case, the assignment works even if the optional
does not have a prior value.
Noncompliant code example
void g(std::optional<int> &val, bool b) {
if (b) {
*val = 314; // Noncompliant, will throw if the optional was previously empty
} else {
val.value() = 42; // Noncompliant, will throw if the optional was previously empty
}
}
Compliant solution
void g(std::optional<int> &val, bool b) {
if (b) {
val = 314; // Compliant
} else {
val = 42; // Compliant
}
}