Menu

False possitive [constParameter] report

Mi-La
2020-02-05
2020-09-22
  • Mi-La

    Mi-La - 2020-02-05

    Hi,
    I didn't want to struggle with creating the track account. I've simple sample of the code firing a false positivy style warning [constParameter ].

    The following code fires (using cppcheck-1.90):

    cppcheck test.cpp --enable=all
    Checking test.cpp ...
    test.cpp:23:37: style: Parameter 'service' can be declared with const [constParameter]
        explicit ClientWrapper(Service& service) : client(service) {}
    

    However the client call a non-const method on the service. Note that when I remove the "ClientWrapper" nad use just the "Client", the warning disappears.

    test.cpp:

    struct Service
    {
        void powerOfTwo(int request, int& response)
        {
            response = request * 2;
        }
    };
    
    struct Client
    {
        explicit Client(Service& service) : service(service) {}
    
        void powerOfTwo(int request, int& response)
        {
            service.powerOfTwo(request, response);
        }
    
        Service& service;
    };
    
    struct ClientWrapper
    {
        explicit ClientWrapper(Service& service) : client(service) {}
    
        int powerOfTwo(int request)
        {
            int response;
            client.powerOfTwo(request, response);
            return response;
        }
    
        Client client;
    };
    
    int main(int argc, char* argv[])
    {
        Service service;
        ClientWrapper client(service);
    
        return client.powerOfTwo(10);
    };
    

    Note that this is only a sample, real service can really do something which requires to have the method non-const - e.g. store something to a database.

     
  • CHR

    CHR - 2020-09-15

    It seems that the example above has been fixed in 2.1. However here is a different one (the non-const overload of GetBuffer() gets called on Dst):

    struct Foo {
        int* Buf{};
        int* GetBuffer() { return Buf; }
        const int* GetBuffer() const { return Buf; }
    };
    
    struct Bar {
        int i{};
        void Convert(Foo& Dst) const { int* p = Dst.GetBuffer(); *p = i; } // Parameter 'Dst' can be declared with const
    };
    
     
  • CHR

    CHR - 2020-09-22

    bump
    Can anyone verify this? Maybe I should have started a new thread...

     
  • Daniel Marjamäki

    Thanks! I can reproduce. I created ticket https://trac.cppcheck.net/ticket/9910

     

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.