Menu

constStatement warning when creating a map of functions

2021-10-27
2021-10-27
  • Marco Paladini

    Marco Paladini - 2021-10-27

    Hi,

    I don't understand why cppcheck shows a constStatement warning (Found a statement that begins with string constant) when I declare a map string->function.

    sample code that reproduces the warning:

    using Function = std::function<int(int)>;
    
    class Executor {
        int foo(int a) { return a; }
        int bar(int a) { return a + 1; }
    
    public:
        Function get_function(const std::string& function_name)
        {
            static std::unordered_map<std::string, Function> function_map{
                // the next two lines produce a constStatement warning: (warning) Redundant code: Found a
                // statement that begins with string constant.
                { "one", [this](int i) -> int { return foo(i); } },
                { "two", [this](int i) -> int { return bar(i); } }
    
            };
            Function function = function_map.at(function_name);
            return function;
        }
    };
    

    using an initialiser list for map string->int shows no warning, maybe there is something to do with the lambda function that trips cppcheck?
    I don't think it should warn me here, the string constants are initialising the map.

    Many thanks

     

    Last edit: Marco Paladini 2021-10-27
  • Daniel Marjamäki

    I fail to reproduce with latest cppcheck. Which version do you use?

     
  • Marco Paladini

    Marco Paladini - 2021-10-27

    oh I have Cppcheck 1.82 on Ubuntu 18.04.
    I should have tried the latest version, my bad. Thanks for the help!

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.