Menu

functionConst false positive

2025-02-16
2025-02-27
  • Nikita Leontiev

    Nikita Leontiev - 2025-02-16

    cppcheck 2.16.0 suggests to use const for method init that changes class member:

    enum Type
    {
        TYPE_1,
        TYPE_2
    };
    
    void getter(int * param)
    {
        *param = 1;
    }
    
    class Test
    {
    private:
        Type type;
    public:
        Test(): type(TYPE_1) {}
    
        void init()
        {
            getter(reinterpret_cast<int*>(&type));
        }
    };
    
    test\main.cpp:19:7: style: inconclusive: Technically the member function 'Test::init' can be const. [functionConst]
     void init()
          ^
    
     

    Last edit: Nikita Leontiev 2025-02-16
  • CHR

    CHR - 2025-02-17

    Thanks for reporting, ticket is here: https://trac.cppcheck.net/ticket/13642

     
  • Nikita Leontiev

    Nikita Leontiev - 2025-02-27

    cppcheck 2.17.1 generates functionConst false positive with slightly modified code:

    #include <cstring>
    
    enum Type
    {
        TYPE_1,
        TYPE_2
    };
    
    void getter(char * type, int * param)
    {
        if (!strcmp(type, "TYPE_2"))
            *param = 1;
    }
    
    class Test
    {
    private:
        Type type;
    public:
        Test(): type(TYPE_1) {}
    
        void init()
        {
            getter("TYPE_2", reinterpret_cast<int*>(&type));
        }
    };
    
    test\main.cpp:22:10: style: inconclusive: Technically the member function 'Test::init' can be const. [functionConst]
        void init()
             ^
    
     
  • CHR

    CHR - 2025-02-27

    The FP disappears when getter() takes a const char*. For the original code, there is a warning:

    <source>:23:16: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
       23 |         getter("TYPE_2", reinterpret_cast<int*>(&type));
          |                ^~~~~~~~
    
     

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.