Menu

unreadVariable with RAII classes

2022-03-23
2022-03-25
  • Daniel Bengtsson

    Hi,

    I am having issues like: style: Variable 'raii' is assigned a value that is never used. [unreadVariable] with our custom raii classes.

    What information is cppcheck missing such that it would know not to warn for such cases? I did use --check-config to see if there were any missing includes. But it only lists various system includes not from my code.

    I am using cppcheck 2.7.3.

     
  • Daniel Marjamäki

    can you please create a small example that reproduce the false positive.

    I would spontanously think that if cppcheck see that raii is a class that might have global side effects during destruction we should not write this warning.

     

    Last edit: Daniel Marjamäki 2022-03-23
  • Daniel Bengtsson

    I worked on minimizing it and ended up with this:

    namespace test {
    
    class RAII {
    public:
      RAII(){}
      ~RAII(){}
    };
    
    }
    
    using namespace test;
    
    int main() {
      auto raii = RAII();
      return 0;
    }
    

    The problem seem to be the using namespace test; , if I remove that and explicitly use test::RAII() the warning goes away.

    I ran it like this:

    cppcheck --std=c++17 --enable=all raii.cpp

    (The compiler are happy with both versions.)

    It also reproduces at https://cppcheck.sourceforge.io/demo/

     
  • CHR

    CHR - 2022-03-24

    There are several issues at play here.
    Cppcheck emits a known false positive with auto, this is tracked here: https://trac.cppcheck.net/ticket/10505
    Declaring the variable as RAII raii; in your example still yields a warning, because cppcheck sees the empty con/destructors. If you then just declare class RAII; (or the con/destructor) inside test, the warning disappears. I did not see any effect of using namespace, but I might be missing something.

     
  • Daniel Bengtsson

    I see, so I guess ticket 10505 is the main issue.

    Regarding the namespace the original code above warns, but this one does not:

    namespace test {
    
    class RAII {
    public:
      RAII(){}
      ~RAII(){}
    };
    
    }
    
    int main() {
      auto raii = test::RAII();
      return 0;
    }
    
     
  • CHR

    CHR - 2022-03-25

    Hmm, with current head I do get a warning:

    bar.cpp:12:8: style: Variable 'raii' is assigned a value that is never used. [unreadVariable]
      auto raii = test::RAII();
           ^
    
     

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.