rspec/rules/S6427/cfamily/rule.adoc

32 lines
1.0 KiB
Plaintext
Raw Normal View History

== 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
[source,cpp]
----
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
[source,cpp]
----
void g(std::optional<int> &val, bool b) {
if (b) {
val = 314; // Compliant
} else {
val = 42; // Compliant
}
}
----