std::optional tested via its bool conversion
ID |
c.maintainability.optional_test_method |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Readability |
Language |
C / C++ |
Description
This condition relies on std::optional’s implicit conversion to `bool to test whether it holds a value. The conversion works, but it reads like an ordinary boolean check and hides that an optional is being tested at all. Call has_value() (or its negation) so the condition states directly what it is checking.
Rationale
This condition relies on std::optional’s implicit conversion to `bool to test whether it holds a value. The conversion works, but it reads like an ordinary boolean check and hides that an optional is being tested at all. Call has_value() (or its negation) so the condition states directly what it is checking.
The following code illustrates the pattern detected by this rule:
void process(std::optional<int> opt, std::optional<int> other)
{
// FLAGGED: std::optional tested via its bool conversion
if (opt) { }
// FLAGGED: std::optional tested via its bool conversion
if (!opt) { }
// FLAGGED: std::optional tested via its bool conversion
while (opt) { }
if (opt.has_value()) { }
if (!opt.has_value()) { }
bool ready = true;
if (ready) { }
(void)other;
}