Assignment through a dereferenced std::optional
ID |
c.correctness.optional_assignment_target |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Api Design |
Language |
C / C++ |
Description
This assigns through a dereferenced std::optional. operator* does not check whether the optional is engaged, so if it holds no value this is undefined behavior. Assign to the optional itself instead of through it, e.g. opt = value;, which both replaces the contents and engages the optional safely regardless of its prior state.
Rationale
This assigns through a dereferenced std::optional. operator* does not check whether the optional is engaged, so if it holds no value this is undefined behavior. Assign to the optional itself instead of through it, e.g. opt = value;, which both replaces the contents and engages the optional safely regardless of its prior state.
The following code illustrates the pattern detected by this rule:
void setValue(std::optional<int> opt, std::optional<std::string> sopt, int v, std::string s, int *raw)
{
// FLAGGED: Assignment through a dereferenced std::optional
*opt = v;
// FLAGGED: Assignment through a dereferenced std::optional
*sopt = s;
opt = v;
*raw = v;
}