Check that std::optional is being checked before use

std::optional was added in C++17 and allows you to have a value that may or may not be present. A basic example:

    std::optional<int> create(bool b) {
        if (b) {
            return 911;
        }
        return {};
    }

    int main() {
        auto result = create(false);
        if (result) {
            std::out << result;
        }
    }

But I noticed that SonarLint isn’t warning you if your code doesn’t check the validity of std::optional. This would be a good check to add, because otherwise you might be using a value that hasn’t been set:

    int main() {
        auto result = create(false);
        std::out << result; // This value hasn't been set
    }

Hello @Tom_Isaacson2 ,

Indeed that would be an interesting, and valuable, rule to have. I have created a ticket in our backlog

https://sonarsource.atlassian.net/browse/CPP-5095

Thanks for the feedback!

2 Likes