Menu

False positive: functionConst when operator[] is used on this

2020-11-12
2020-11-12
  • Andreas Grob

    Andreas Grob - 2020-11-12
    struct A {
        int a = 0;
    
        auto operator[](int x) -> int & {
            a = 1;
            return a;
        }
    
        int test() {
            return (*this)[0]; // no FP with this->operator[](0)
        }
    };
    

    With 324e267:

    $ cppcheck --debug-normal --enable=style --inconclusive test.cpp 
    Checking test.cpp ...
    
    
    ##file test.cpp
    1: struct A {
    2: int a ; a = 0 ;
    3:
    4: auto operator[] ( int x ) . int & {
    5: a@1 = 1 ;
    6: return a@1 ;
    7: }
    8:
    9: int test ( ) {
    10: return (@3 *@4 this ) [ 0 ] ;
    11: }
    12: } ;
    
    
    
    ##Value flow
    Line 2
      0 always 0
    Line 5
      1 always 1
    Line 10
      0 always 0
    test.cpp:9:9: style:inconclusive: Technically the member function 'A::test' can be const. [functionConst]
        int test() {
            ^
    
     
  • Daniel Marjamäki

    we need better handling of overloaded operators in cppcheck.

    however it seems unfortunate for this case to tweak cppcheck

    personally I think in principle that it's best if overloaded operators are consistent with standard behavior and Cppcheck makes some assumptions about that.. With such assumptions I believe we can simplify analysis and make it stronger.

    You could implement a method instead if you don't intend to have standard behavior.. A::setA(int x). What do you think?

    Maybe there should be a flag in Cppcheck .. if your overloaded operators are inconsistent then make analysis weaker. If overloaded operators are consistent Cppcheck can use stronger analysis.

     

    Last edit: Daniel Marjamäki 2020-11-12
  • Andreas Grob

    Andreas Grob - 2020-11-12

    I agree that the code I found looks a bit unfortunate.

    Which standard behavior are you referencing or assuming?

     
  • Andreas Grob

    Andreas Grob - 2020-11-12

    The original code does access a container with internal side effects, like e.g. std::map::operator[].
    I just reduced this test to make it shorter.

     
  • Daniel Marjamäki

    The original code does access a container with internal side effects, like e.g. std::map::operator[].

    hmm.. we should assume there can be such side effects. thanks!

     
  • Daniel Marjamäki

     

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.