Chỉnh sửa

Chia sẻ qua


Warning C26830

Potentially empty optional 'variable' is unwrapped

Remarks

Unwrapping empty std::optional values is undefined behavior. Such operation is considered a security vulnerability as it can result in a crash, reading uninitialized memory, or other unexpected behavior. This check will attempt to find cases where a std::optional isn't checked for emptiness before unwrap operations. You can enable C26829 only for a more permissive analysis.

Example

std::optional<int> getOptional();

void f(std::optional<int> maybeEmpty)
{
    if (maybeEmpty)
        *maybeEmpty = 42; // No warning
    *maybeEmpty = 5; // warning: C26830
    std::optional<int> o = getOptional();
    *o = 42; // warning: C26830
}

To solve this problem, make sure the code never unwraps an empty optional. Alternatively, use the value method and make sure you handle the std::bad_optional_access exception.