Breyta

Warning C26859

Empty optional 'variable' is unwrapped, will throw exception

Remarks

Unwrapping empty std::optional values via the value method will throw an exception. Such operation can result in a crash when the exception isn't handled. This check will attempt to find cases where a std::optional is known to be empty and unwrapped using the value method. You can also enable C26829, C26830, and C26860 for a stricter analysis.

Example

void f(std::optional<int> maybeEmpty)
{
    std::optional<int> empty;
    std::optional<int> nonEmpty{5};
    nonEmpty.value() = 42; // No warning
    empty.value() = 42; // warning: C26859
    if (!maybeEmpty)
        maybeEmpty.value() = 42; // warning: C26859
}

To solve this problem, make sure the code never unwraps an empty optional.